9303a5cd5f247c087c3324620eb8938d8a50d5ae
[lhc/web/wiklou.git] / includes / Title.php
1 <?php
2 /**
3 * Representation of a title within %MediaWiki.
4 *
5 * See title.txt
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
21 *
22 * @file
23 */
24
25 use Wikimedia\Rdbms\Database;
26 use Wikimedia\Rdbms\IDatabase;
27 use MediaWiki\Linker\LinkTarget;
28 use MediaWiki\Interwiki\InterwikiLookup;
29 use MediaWiki\MediaWikiServices;
30
31 /**
32 * Represents a title within MediaWiki.
33 * Optionally may contain an interwiki designation or namespace.
34 * @note This class can fetch various kinds of data from the database;
35 * however, it does so inefficiently.
36 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
37 * and does not rely on global state or the database.
38 */
39 class Title implements LinkTarget, IDBAccessObject {
40 /** @var MapCacheLRU */
41 private static $titleCache = null;
42
43 /**
44 * Title::newFromText maintains a cache to avoid expensive re-normalization of
45 * commonly used titles. On a batch operation this can become a memory leak
46 * if not bounded. After hitting this many titles reset the cache.
47 */
48 const CACHE_MAX = 1000;
49
50 /**
51 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
52 * to use the master DB
53 */
54 const GAID_FOR_UPDATE = 1;
55
56 /**
57 * @name Private member variables
58 * Please use the accessor functions instead.
59 * @private
60 */
61 // @{
62
63 /** @var string Text form (spaces not underscores) of the main part */
64 public $mTextform = '';
65
66 /** @var string URL-encoded form of the main part */
67 public $mUrlform = '';
68
69 /** @var string Main part with underscores */
70 public $mDbkeyform = '';
71
72 /** @var string Database key with the initial letter in the case specified by the user */
73 protected $mUserCaseDBKey;
74
75 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
76 public $mNamespace = NS_MAIN;
77
78 /** @var string Interwiki prefix */
79 public $mInterwiki = '';
80
81 /** @var bool Was this Title created from a string with a local interwiki prefix? */
82 private $mLocalInterwiki = false;
83
84 /** @var string Title fragment (i.e. the bit after the #) */
85 public $mFragment = '';
86
87 /** @var int Article ID, fetched from the link cache on demand */
88 public $mArticleID = -1;
89
90 /** @var bool|int ID of most recent revision */
91 protected $mLatestID = false;
92
93 /**
94 * @var bool|string ID of the page's content model, i.e. one of the
95 * CONTENT_MODEL_XXX constants
96 */
97 private $mContentModel = false;
98
99 /**
100 * @var bool If a content model was forced via setContentModel()
101 * this will be true to avoid having other code paths reset it
102 */
103 private $mForcedContentModel = false;
104
105 /** @var int Estimated number of revisions; null of not loaded */
106 private $mEstimateRevisions;
107
108 /** @var array Array of groups allowed to edit this article */
109 public $mRestrictions = [];
110
111 /**
112 * @var string|bool Comma-separated set of permission keys
113 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
114 * Edit and move sections are separated by a colon
115 * Example: "edit=autoconfirmed,sysop:move=sysop"
116 */
117 protected $mOldRestrictions = false;
118
119 /** @var bool Cascade restrictions on this page to included templates and images? */
120 public $mCascadeRestriction;
121
122 /** Caching the results of getCascadeProtectionSources */
123 public $mCascadingRestrictions;
124
125 /** @var array When do the restrictions on this page expire? */
126 protected $mRestrictionsExpiry = [];
127
128 /** @var bool Are cascading restrictions in effect on this page? */
129 protected $mHasCascadingRestrictions;
130
131 /** @var array Where are the cascading restrictions coming from on this page? */
132 public $mCascadeSources;
133
134 /** @var bool Boolean for initialisation on demand */
135 public $mRestrictionsLoaded = false;
136
137 /**
138 * Text form including namespace/interwiki, initialised on demand
139 *
140 * Only public to share cache with TitleFormatter
141 *
142 * @private
143 * @var string
144 */
145 public $prefixedText = null;
146
147 /** @var mixed Cached value for getTitleProtection (create protection) */
148 public $mTitleProtection;
149
150 /**
151 * @var int Namespace index when there is no namespace. Don't change the
152 * following default, NS_MAIN is hardcoded in several places. See T2696.
153 * Zero except in {{transclusion}} tags.
154 */
155 public $mDefaultNamespace = NS_MAIN;
156
157 /** @var int The page length, 0 for special pages */
158 protected $mLength = -1;
159
160 /** @var null Is the article at this title a redirect? */
161 public $mRedirect = null;
162
163 /** @var array Associative array of user ID -> timestamp/false */
164 private $mNotificationTimestamp = [];
165
166 /** @var bool Whether a page has any subpages */
167 private $mHasSubpages;
168
169 /** @var bool The (string) language code of the page's language and content code. */
170 private $mPageLanguage = false;
171
172 /** @var string|bool|null The page language code from the database, null if not saved in
173 * the database or false if not loaded, yet. */
174 private $mDbPageLanguage = false;
175
176 /** @var TitleValue A corresponding TitleValue object */
177 private $mTitleValue = null;
178
179 /** @var bool Would deleting this page be a big deletion? */
180 private $mIsBigDeletion = null;
181 // @}
182
183 /**
184 * B/C kludge: provide a TitleParser for use by Title.
185 * Ideally, Title would have no methods that need this.
186 * Avoid usage of this singleton by using TitleValue
187 * and the associated services when possible.
188 *
189 * @return TitleFormatter
190 */
191 private static function getTitleFormatter() {
192 return MediaWikiServices::getInstance()->getTitleFormatter();
193 }
194
195 /**
196 * B/C kludge: provide an InterwikiLookup for use by Title.
197 * Ideally, Title would have no methods that need this.
198 * Avoid usage of this singleton by using TitleValue
199 * and the associated services when possible.
200 *
201 * @return InterwikiLookup
202 */
203 private static function getInterwikiLookup() {
204 return MediaWikiServices::getInstance()->getInterwikiLookup();
205 }
206
207 /**
208 * @protected
209 */
210 function __construct() {
211 }
212
213 /**
214 * Create a new Title from a prefixed DB key
215 *
216 * @param string $key The database key, which has underscores
217 * instead of spaces, possibly including namespace and
218 * interwiki prefixes
219 * @return Title|null Title, or null on an error
220 */
221 public static function newFromDBkey( $key ) {
222 $t = new Title();
223 $t->mDbkeyform = $key;
224
225 try {
226 $t->secureAndSplit();
227 return $t;
228 } catch ( MalformedTitleException $ex ) {
229 return null;
230 }
231 }
232
233 /**
234 * Create a new Title from a TitleValue
235 *
236 * @param TitleValue $titleValue Assumed to be safe.
237 *
238 * @return Title
239 */
240 public static function newFromTitleValue( TitleValue $titleValue ) {
241 return self::newFromLinkTarget( $titleValue );
242 }
243
244 /**
245 * Create a new Title from a LinkTarget
246 *
247 * @param LinkTarget $linkTarget Assumed to be safe.
248 *
249 * @return Title
250 */
251 public static function newFromLinkTarget( LinkTarget $linkTarget ) {
252 if ( $linkTarget instanceof Title ) {
253 // Special case if it's already a Title object
254 return $linkTarget;
255 }
256 return self::makeTitle(
257 $linkTarget->getNamespace(),
258 $linkTarget->getText(),
259 $linkTarget->getFragment(),
260 $linkTarget->getInterwiki()
261 );
262 }
263
264 /**
265 * Create a new Title from text, such as what one would find in a link. De-
266 * codes any HTML entities in the text.
267 *
268 * Title objects returned by this method are guaranteed to be valid, and
269 * thus return true from the isValid() method.
270 *
271 * @param string|int|null $text The link text; spaces, prefixes, and an
272 * initial ':' indicating the main namespace are accepted.
273 * @param int $defaultNamespace The namespace to use if none is specified
274 * by a prefix. If you want to force a specific namespace even if
275 * $text might begin with a namespace prefix, use makeTitle() or
276 * makeTitleSafe().
277 * @throws InvalidArgumentException
278 * @return Title|null Title or null on an error.
279 */
280 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
281 // DWIM: Integers can be passed in here when page titles are used as array keys.
282 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
283 throw new InvalidArgumentException( '$text must be a string.' );
284 }
285 if ( $text === null ) {
286 return null;
287 }
288
289 try {
290 return self::newFromTextThrow( strval( $text ), $defaultNamespace );
291 } catch ( MalformedTitleException $ex ) {
292 return null;
293 }
294 }
295
296 /**
297 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
298 * rather than returning null.
299 *
300 * The exception subclasses encode detailed information about why the title is invalid.
301 *
302 * Title objects returned by this method are guaranteed to be valid, and
303 * thus return true from the isValid() method.
304 *
305 * @see Title::newFromText
306 *
307 * @since 1.25
308 * @param string $text Title text to check
309 * @param int $defaultNamespace
310 * @throws MalformedTitleException If the title is invalid
311 * @return Title
312 */
313 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN ) {
314 if ( is_object( $text ) ) {
315 throw new MWException( '$text must be a string, given an object' );
316 } elseif ( $text === null ) {
317 // Legacy code relies on MalformedTitleException being thrown in this case
318 // (happens when URL with no title in it is parsed). TODO fix
319 throw new MalformedTitleException( 'title-invalid-empty' );
320 }
321
322 $titleCache = self::getTitleCache();
323
324 // Wiki pages often contain multiple links to the same page.
325 // Title normalization and parsing can become expensive on pages with many
326 // links, so we can save a little time by caching them.
327 // In theory these are value objects and won't get changed...
328 if ( $defaultNamespace == NS_MAIN ) {
329 $t = $titleCache->get( $text );
330 if ( $t ) {
331 return $t;
332 }
333 }
334
335 // Convert things like &eacute; &#257; or &#x3017; into normalized (T16952) text
336 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
337
338 $t = new Title();
339 $t->mDbkeyform = strtr( $filteredText, ' ', '_' );
340 $t->mDefaultNamespace = intval( $defaultNamespace );
341
342 $t->secureAndSplit();
343 if ( $defaultNamespace == NS_MAIN ) {
344 $titleCache->set( $text, $t );
345 }
346 return $t;
347 }
348
349 /**
350 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
351 *
352 * Example of wrong and broken code:
353 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
354 *
355 * Example of right code:
356 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
357 *
358 * Create a new Title from URL-encoded text. Ensures that
359 * the given title's length does not exceed the maximum.
360 *
361 * @param string $url The title, as might be taken from a URL
362 * @return Title|null The new object, or null on an error
363 */
364 public static function newFromURL( $url ) {
365 $t = new Title();
366
367 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
368 # but some URLs used it as a space replacement and they still come
369 # from some external search tools.
370 if ( strpos( self::legalChars(), '+' ) === false ) {
371 $url = strtr( $url, '+', ' ' );
372 }
373
374 $t->mDbkeyform = strtr( $url, ' ', '_' );
375
376 try {
377 $t->secureAndSplit();
378 return $t;
379 } catch ( MalformedTitleException $ex ) {
380 return null;
381 }
382 }
383
384 /**
385 * @return MapCacheLRU
386 */
387 private static function getTitleCache() {
388 if ( self::$titleCache == null ) {
389 self::$titleCache = new MapCacheLRU( self::CACHE_MAX );
390 }
391 return self::$titleCache;
392 }
393
394 /**
395 * Returns a list of fields that are to be selected for initializing Title
396 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
397 * whether to include page_content_model.
398 *
399 * @return array
400 */
401 protected static function getSelectFields() {
402 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
403
404 $fields = [
405 'page_namespace', 'page_title', 'page_id',
406 'page_len', 'page_is_redirect', 'page_latest',
407 ];
408
409 if ( $wgContentHandlerUseDB ) {
410 $fields[] = 'page_content_model';
411 }
412
413 if ( $wgPageLanguageUseDB ) {
414 $fields[] = 'page_lang';
415 }
416
417 return $fields;
418 }
419
420 /**
421 * Create a new Title from an article ID
422 *
423 * @param int $id The page_id corresponding to the Title to create
424 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
425 * @return Title|null The new object, or null on an error
426 */
427 public static function newFromID( $id, $flags = 0 ) {
428 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_REPLICA );
429 $row = $db->selectRow(
430 'page',
431 self::getSelectFields(),
432 [ 'page_id' => $id ],
433 __METHOD__
434 );
435 if ( $row !== false ) {
436 $title = self::newFromRow( $row );
437 } else {
438 $title = null;
439 }
440 return $title;
441 }
442
443 /**
444 * Make an array of titles from an array of IDs
445 *
446 * @param int[] $ids Array of IDs
447 * @return Title[] Array of Titles
448 */
449 public static function newFromIDs( $ids ) {
450 if ( !count( $ids ) ) {
451 return [];
452 }
453 $dbr = wfGetDB( DB_REPLICA );
454
455 $res = $dbr->select(
456 'page',
457 self::getSelectFields(),
458 [ 'page_id' => $ids ],
459 __METHOD__
460 );
461
462 $titles = [];
463 foreach ( $res as $row ) {
464 $titles[] = self::newFromRow( $row );
465 }
466 return $titles;
467 }
468
469 /**
470 * Make a Title object from a DB row
471 *
472 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
473 * @return Title Corresponding Title
474 */
475 public static function newFromRow( $row ) {
476 $t = self::makeTitle( $row->page_namespace, $row->page_title );
477 $t->loadFromRow( $row );
478 return $t;
479 }
480
481 /**
482 * Load Title object fields from a DB row.
483 * If false is given, the title will be treated as non-existing.
484 *
485 * @param stdClass|bool $row Database row
486 */
487 public function loadFromRow( $row ) {
488 if ( $row ) { // page found
489 if ( isset( $row->page_id ) ) {
490 $this->mArticleID = (int)$row->page_id;
491 }
492 if ( isset( $row->page_len ) ) {
493 $this->mLength = (int)$row->page_len;
494 }
495 if ( isset( $row->page_is_redirect ) ) {
496 $this->mRedirect = (bool)$row->page_is_redirect;
497 }
498 if ( isset( $row->page_latest ) ) {
499 $this->mLatestID = (int)$row->page_latest;
500 }
501 if ( !$this->mForcedContentModel && isset( $row->page_content_model ) ) {
502 $this->mContentModel = strval( $row->page_content_model );
503 } elseif ( !$this->mForcedContentModel ) {
504 $this->mContentModel = false; # initialized lazily in getContentModel()
505 }
506 if ( isset( $row->page_lang ) ) {
507 $this->mDbPageLanguage = (string)$row->page_lang;
508 }
509 if ( isset( $row->page_restrictions ) ) {
510 $this->mOldRestrictions = $row->page_restrictions;
511 }
512 } else { // page not found
513 $this->mArticleID = 0;
514 $this->mLength = 0;
515 $this->mRedirect = false;
516 $this->mLatestID = 0;
517 if ( !$this->mForcedContentModel ) {
518 $this->mContentModel = false; # initialized lazily in getContentModel()
519 }
520 }
521 }
522
523 /**
524 * Create a new Title from a namespace index and a DB key.
525 *
526 * It's assumed that $ns and $title are safe, for instance when
527 * they came directly from the database or a special page name,
528 * not from user input.
529 *
530 * No validation is applied. For convenience, spaces are normalized
531 * to underscores, so that e.g. user_text fields can be used directly.
532 *
533 * @note This method may return Title objects that are "invalid"
534 * according to the isValid() method. This is usually caused by
535 * configuration changes: e.g. a namespace that was once defined is
536 * no longer configured, or a character that was once allowed in
537 * titles is now forbidden.
538 *
539 * @param int $ns The namespace of the article
540 * @param string $title The unprefixed database key form
541 * @param string $fragment The link fragment (after the "#")
542 * @param string $interwiki The interwiki prefix
543 * @return Title The new object
544 */
545 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
546 $t = new Title();
547 $t->mInterwiki = $interwiki;
548 $t->mFragment = $fragment;
549 $t->mNamespace = $ns = intval( $ns );
550 $t->mDbkeyform = strtr( $title, ' ', '_' );
551 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
552 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
553 $t->mTextform = strtr( $title, '_', ' ' );
554 $t->mContentModel = false; # initialized lazily in getContentModel()
555 return $t;
556 }
557
558 /**
559 * Create a new Title from a namespace index and a DB key.
560 * The parameters will be checked for validity, which is a bit slower
561 * than makeTitle() but safer for user-provided data.
562 *
563 * Title objects returned by makeTitleSafe() are guaranteed to be valid,
564 * that is, they return true from the isValid() method. If no valid Title
565 * can be constructed from the input, this method returns null.
566 *
567 * @param int $ns The namespace of the article
568 * @param string $title Database key form
569 * @param string $fragment The link fragment (after the "#")
570 * @param string $interwiki Interwiki prefix
571 * @return Title|null The new object, or null on an error
572 */
573 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
574 // NOTE: ideally, this would just call makeTitle() and then isValid(),
575 // but presently, that means more overhead on a potential performance hotspot.
576
577 if ( !MWNamespace::exists( $ns ) ) {
578 return null;
579 }
580
581 $t = new Title();
582 $t->mDbkeyform = self::makeName( $ns, $title, $fragment, $interwiki, true );
583
584 try {
585 $t->secureAndSplit();
586 return $t;
587 } catch ( MalformedTitleException $ex ) {
588 return null;
589 }
590 }
591
592 /**
593 * Create a new Title for the Main Page
594 *
595 * @return Title The new object
596 */
597 public static function newMainPage() {
598 $title = self::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
599 // Don't give fatal errors if the message is broken
600 if ( !$title ) {
601 $title = self::newFromText( 'Main Page' );
602 }
603 return $title;
604 }
605
606 /**
607 * Get the prefixed DB key associated with an ID
608 *
609 * @param int $id The page_id of the article
610 * @return Title|null An object representing the article, or null if no such article was found
611 */
612 public static function nameOf( $id ) {
613 $dbr = wfGetDB( DB_REPLICA );
614
615 $s = $dbr->selectRow(
616 'page',
617 [ 'page_namespace', 'page_title' ],
618 [ 'page_id' => $id ],
619 __METHOD__
620 );
621 if ( $s === false ) {
622 return null;
623 }
624
625 $n = self::makeName( $s->page_namespace, $s->page_title );
626 return $n;
627 }
628
629 /**
630 * Get a regex character class describing the legal characters in a link
631 *
632 * @return string The list of characters, not delimited
633 */
634 public static function legalChars() {
635 global $wgLegalTitleChars;
636 return $wgLegalTitleChars;
637 }
638
639 /**
640 * Utility method for converting a character sequence from bytes to Unicode.
641 *
642 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
643 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
644 *
645 * @param string $byteClass
646 * @return string
647 */
648 public static function convertByteClassToUnicodeClass( $byteClass ) {
649 $length = strlen( $byteClass );
650 // Input token queue
651 $x0 = $x1 = $x2 = '';
652 // Decoded queue
653 $d0 = $d1 = $d2 = '';
654 // Decoded integer codepoints
655 $ord0 = $ord1 = $ord2 = 0;
656 // Re-encoded queue
657 $r0 = $r1 = $r2 = '';
658 // Output
659 $out = '';
660 // Flags
661 $allowUnicode = false;
662 for ( $pos = 0; $pos < $length; $pos++ ) {
663 // Shift the queues down
664 $x2 = $x1;
665 $x1 = $x0;
666 $d2 = $d1;
667 $d1 = $d0;
668 $ord2 = $ord1;
669 $ord1 = $ord0;
670 $r2 = $r1;
671 $r1 = $r0;
672 // Load the current input token and decoded values
673 $inChar = $byteClass[$pos];
674 if ( $inChar == '\\' ) {
675 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos + 1 ) ) {
676 $x0 = $inChar . $m[0];
677 $d0 = chr( hexdec( $m[1] ) );
678 $pos += strlen( $m[0] );
679 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos + 1 ) ) {
680 $x0 = $inChar . $m[0];
681 $d0 = chr( octdec( $m[0] ) );
682 $pos += strlen( $m[0] );
683 } elseif ( $pos + 1 >= $length ) {
684 $x0 = $d0 = '\\';
685 } else {
686 $d0 = $byteClass[$pos + 1];
687 $x0 = $inChar . $d0;
688 $pos += 1;
689 }
690 } else {
691 $x0 = $d0 = $inChar;
692 }
693 $ord0 = ord( $d0 );
694 // Load the current re-encoded value
695 if ( $ord0 < 32 || $ord0 == 0x7f ) {
696 $r0 = sprintf( '\x%02x', $ord0 );
697 } elseif ( $ord0 >= 0x80 ) {
698 // Allow unicode if a single high-bit character appears
699 $r0 = sprintf( '\x%02x', $ord0 );
700 $allowUnicode = true;
701 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
702 $r0 = '\\' . $d0;
703 } else {
704 $r0 = $d0;
705 }
706 // Do the output
707 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
708 // Range
709 if ( $ord2 > $ord0 ) {
710 // Empty range
711 } elseif ( $ord0 >= 0x80 ) {
712 // Unicode range
713 $allowUnicode = true;
714 if ( $ord2 < 0x80 ) {
715 // Keep the non-unicode section of the range
716 $out .= "$r2-\\x7F";
717 }
718 } else {
719 // Normal range
720 $out .= "$r2-$r0";
721 }
722 // Reset state to the initial value
723 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
724 } elseif ( $ord2 < 0x80 ) {
725 // ASCII character
726 $out .= $r2;
727 }
728 }
729 if ( $ord1 < 0x80 ) {
730 $out .= $r1;
731 }
732 if ( $ord0 < 0x80 ) {
733 $out .= $r0;
734 }
735 if ( $allowUnicode ) {
736 $out .= '\u0080-\uFFFF';
737 }
738 return $out;
739 }
740
741 /**
742 * Make a prefixed DB key from a DB key and a namespace index
743 *
744 * @param int $ns Numerical representation of the namespace
745 * @param string $title The DB key form the title
746 * @param string $fragment The link fragment (after the "#")
747 * @param string $interwiki The interwiki prefix
748 * @param bool $canonicalNamespace If true, use the canonical name for
749 * $ns instead of the localized version.
750 * @return string The prefixed form of the title
751 */
752 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
753 $canonicalNamespace = false
754 ) {
755 if ( $canonicalNamespace ) {
756 $namespace = MWNamespace::getCanonicalName( $ns );
757 } else {
758 $namespace = MediaWikiServices::getInstance()->getContentLanguage()->getNsText( $ns );
759 }
760 $name = $namespace == '' ? $title : "$namespace:$title";
761 if ( strval( $interwiki ) != '' ) {
762 $name = "$interwiki:$name";
763 }
764 if ( strval( $fragment ) != '' ) {
765 $name .= '#' . $fragment;
766 }
767 return $name;
768 }
769
770 /**
771 * Callback for usort() to do title sorts by (namespace, title)
772 *
773 * @param LinkTarget $a
774 * @param LinkTarget $b
775 *
776 * @return int Result of string comparison, or namespace comparison
777 */
778 public static function compare( LinkTarget $a, LinkTarget $b ) {
779 return $a->getNamespace() <=> $b->getNamespace()
780 ?: strcmp( $a->getText(), $b->getText() );
781 }
782
783 /**
784 * Returns true if the title is valid, false if it is invalid.
785 *
786 * Valid titles can be round-tripped via makeTitleSafe() and newFromText().
787 * Invalid titles may get returned from makeTitle(), and it may be useful to
788 * allow them to exist, e.g. in order to process log entries about pages in
789 * namespaces that belong to extensions that are no longer installed.
790 *
791 * @note This method is relatively expensive. When constructing Title
792 * objects that need to be valid, use an instantiator method that is guaranteed
793 * to return valid titles, such as makeTitleSafe() or newFromText().
794 *
795 * @return bool
796 */
797 public function isValid() {
798 if ( !MWNamespace::exists( $this->mNamespace ) ) {
799 return false;
800 }
801
802 try {
803 $parser = MediaWikiServices::getInstance()->getTitleParser();
804 $parser->parseTitle( $this->mDbkeyform, $this->mNamespace );
805 return true;
806 } catch ( MalformedTitleException $ex ) {
807 return false;
808 }
809 }
810
811 /**
812 * Determine whether the object refers to a page within
813 * this project (either this wiki or a wiki with a local
814 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
815 *
816 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
817 */
818 public function isLocal() {
819 if ( $this->isExternal() ) {
820 $iw = self::getInterwikiLookup()->fetch( $this->mInterwiki );
821 if ( $iw ) {
822 return $iw->isLocal();
823 }
824 }
825 return true;
826 }
827
828 /**
829 * Is this Title interwiki?
830 *
831 * @return bool
832 */
833 public function isExternal() {
834 return $this->mInterwiki !== '';
835 }
836
837 /**
838 * Get the interwiki prefix
839 *
840 * Use Title::isExternal to check if a interwiki is set
841 *
842 * @return string Interwiki prefix
843 */
844 public function getInterwiki() {
845 return $this->mInterwiki;
846 }
847
848 /**
849 * Was this a local interwiki link?
850 *
851 * @return bool
852 */
853 public function wasLocalInterwiki() {
854 return $this->mLocalInterwiki;
855 }
856
857 /**
858 * Determine whether the object refers to a page within
859 * this project and is transcludable.
860 *
861 * @return bool True if this is transcludable
862 */
863 public function isTrans() {
864 if ( !$this->isExternal() ) {
865 return false;
866 }
867
868 return self::getInterwikiLookup()->fetch( $this->mInterwiki )->isTranscludable();
869 }
870
871 /**
872 * Returns the DB name of the distant wiki which owns the object.
873 *
874 * @return string|false The DB name
875 */
876 public function getTransWikiID() {
877 if ( !$this->isExternal() ) {
878 return false;
879 }
880
881 return self::getInterwikiLookup()->fetch( $this->mInterwiki )->getWikiID();
882 }
883
884 /**
885 * Get a TitleValue object representing this Title.
886 *
887 * @note Not all valid Titles have a corresponding valid TitleValue
888 * (e.g. TitleValues cannot represent page-local links that have a
889 * fragment but no title text).
890 *
891 * @return TitleValue|null
892 */
893 public function getTitleValue() {
894 if ( $this->mTitleValue === null ) {
895 try {
896 $this->mTitleValue = new TitleValue(
897 $this->mNamespace,
898 $this->mDbkeyform,
899 $this->mFragment,
900 $this->mInterwiki
901 );
902 } catch ( InvalidArgumentException $ex ) {
903 wfDebug( __METHOD__ . ': Can\'t create a TitleValue for [[' .
904 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
905 }
906 }
907
908 return $this->mTitleValue;
909 }
910
911 /**
912 * Get the text form (spaces not underscores) of the main part
913 *
914 * @return string Main part of the title
915 */
916 public function getText() {
917 return $this->mTextform;
918 }
919
920 /**
921 * Get the URL-encoded form of the main part
922 *
923 * @return string Main part of the title, URL-encoded
924 */
925 public function getPartialURL() {
926 return $this->mUrlform;
927 }
928
929 /**
930 * Get the main part with underscores
931 *
932 * @return string Main part of the title, with underscores
933 */
934 public function getDBkey() {
935 return $this->mDbkeyform;
936 }
937
938 /**
939 * Get the DB key with the initial letter case as specified by the user
940 * @deprecated since 1.33; please use Title::getDBKey() instead
941 *
942 * @return string DB key
943 */
944 function getUserCaseDBKey() {
945 if ( !is_null( $this->mUserCaseDBKey ) ) {
946 return $this->mUserCaseDBKey;
947 } else {
948 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
949 return $this->mDbkeyform;
950 }
951 }
952
953 /**
954 * Get the namespace index, i.e. one of the NS_xxxx constants.
955 *
956 * @return int Namespace index
957 */
958 public function getNamespace() {
959 return $this->mNamespace;
960 }
961
962 /**
963 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
964 *
965 * @todo Deprecate this in favor of SlotRecord::getModel()
966 *
967 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
968 * @return string Content model id
969 */
970 public function getContentModel( $flags = 0 ) {
971 if ( !$this->mForcedContentModel
972 && ( !$this->mContentModel || $flags === self::GAID_FOR_UPDATE )
973 && $this->getArticleID( $flags )
974 ) {
975 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
976 $linkCache->addLinkObj( $this ); # in case we already had an article ID
977 $this->mContentModel = $linkCache->getGoodLinkFieldObj( $this, 'model' );
978 }
979
980 if ( !$this->mContentModel ) {
981 $this->mContentModel = ContentHandler::getDefaultModelFor( $this );
982 }
983
984 return $this->mContentModel;
985 }
986
987 /**
988 * Convenience method for checking a title's content model name
989 *
990 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
991 * @return bool True if $this->getContentModel() == $id
992 */
993 public function hasContentModel( $id ) {
994 return $this->getContentModel() == $id;
995 }
996
997 /**
998 * Set a proposed content model for the page for permissions
999 * checking. This does not actually change the content model
1000 * of a title!
1001 *
1002 * Additionally, you should make sure you've checked
1003 * ContentHandler::canBeUsedOn() first.
1004 *
1005 * @since 1.28
1006 * @param string $model CONTENT_MODEL_XXX constant
1007 */
1008 public function setContentModel( $model ) {
1009 $this->mContentModel = $model;
1010 $this->mForcedContentModel = true;
1011 }
1012
1013 /**
1014 * Get the namespace text
1015 *
1016 * @return string|false Namespace text
1017 */
1018 public function getNsText() {
1019 if ( $this->isExternal() ) {
1020 // This probably shouldn't even happen, except for interwiki transclusion.
1021 // If possible, use the canonical name for the foreign namespace.
1022 $nsText = MWNamespace::getCanonicalName( $this->mNamespace );
1023 if ( $nsText !== false ) {
1024 return $nsText;
1025 }
1026 }
1027
1028 try {
1029 $formatter = self::getTitleFormatter();
1030 return $formatter->getNamespaceName( $this->mNamespace, $this->mDbkeyform );
1031 } catch ( InvalidArgumentException $ex ) {
1032 wfDebug( __METHOD__ . ': ' . $ex->getMessage() . "\n" );
1033 return false;
1034 }
1035 }
1036
1037 /**
1038 * Get the namespace text of the subject (rather than talk) page
1039 *
1040 * @return string Namespace text
1041 */
1042 public function getSubjectNsText() {
1043 return MediaWikiServices::getInstance()->getContentLanguage()->
1044 getNsText( MWNamespace::getSubject( $this->mNamespace ) );
1045 }
1046
1047 /**
1048 * Get the namespace text of the talk page
1049 *
1050 * @return string Namespace text
1051 */
1052 public function getTalkNsText() {
1053 return MediaWikiServices::getInstance()->getContentLanguage()->
1054 getNsText( MWNamespace::getTalk( $this->mNamespace ) );
1055 }
1056
1057 /**
1058 * Can this title have a corresponding talk page?
1059 *
1060 * @deprecated since 1.30, use canHaveTalkPage() instead.
1061 *
1062 * @return bool True if this title either is a talk page or can have a talk page associated.
1063 */
1064 public function canTalk() {
1065 return $this->canHaveTalkPage();
1066 }
1067
1068 /**
1069 * Can this title have a corresponding talk page?
1070 *
1071 * @see MWNamespace::hasTalkNamespace
1072 * @since 1.30
1073 *
1074 * @return bool True if this title either is a talk page or can have a talk page associated.
1075 */
1076 public function canHaveTalkPage() {
1077 return MWNamespace::hasTalkNamespace( $this->mNamespace );
1078 }
1079
1080 /**
1081 * Is this in a namespace that allows actual pages?
1082 *
1083 * @return bool
1084 */
1085 public function canExist() {
1086 return $this->mNamespace >= NS_MAIN;
1087 }
1088
1089 /**
1090 * Can this title be added to a user's watchlist?
1091 *
1092 * @return bool
1093 */
1094 public function isWatchable() {
1095 return !$this->isExternal() && MWNamespace::isWatchable( $this->mNamespace );
1096 }
1097
1098 /**
1099 * Returns true if this is a special page.
1100 *
1101 * @return bool
1102 */
1103 public function isSpecialPage() {
1104 return $this->mNamespace == NS_SPECIAL;
1105 }
1106
1107 /**
1108 * Returns true if this title resolves to the named special page
1109 *
1110 * @param string $name The special page name
1111 * @return bool
1112 */
1113 public function isSpecial( $name ) {
1114 if ( $this->isSpecialPage() ) {
1115 list( $thisName, /* $subpage */ ) =
1116 MediaWikiServices::getInstance()->getSpecialPageFactory()->
1117 resolveAlias( $this->mDbkeyform );
1118 if ( $name == $thisName ) {
1119 return true;
1120 }
1121 }
1122 return false;
1123 }
1124
1125 /**
1126 * If the Title refers to a special page alias which is not the local default, resolve
1127 * the alias, and localise the name as necessary. Otherwise, return $this
1128 *
1129 * @return Title
1130 */
1131 public function fixSpecialName() {
1132 if ( $this->isSpecialPage() ) {
1133 $spFactory = MediaWikiServices::getInstance()->getSpecialPageFactory();
1134 list( $canonicalName, $par ) = $spFactory->resolveAlias( $this->mDbkeyform );
1135 if ( $canonicalName ) {
1136 $localName = $spFactory->getLocalNameFor( $canonicalName, $par );
1137 if ( $localName != $this->mDbkeyform ) {
1138 return self::makeTitle( NS_SPECIAL, $localName );
1139 }
1140 }
1141 }
1142 return $this;
1143 }
1144
1145 /**
1146 * Returns true if the title is inside the specified namespace.
1147 *
1148 * Please make use of this instead of comparing to getNamespace()
1149 * This function is much more resistant to changes we may make
1150 * to namespaces than code that makes direct comparisons.
1151 * @param int $ns The namespace
1152 * @return bool
1153 * @since 1.19
1154 */
1155 public function inNamespace( $ns ) {
1156 return MWNamespace::equals( $this->mNamespace, $ns );
1157 }
1158
1159 /**
1160 * Returns true if the title is inside one of the specified namespaces.
1161 *
1162 * @param int|int[] $namespaces,... The namespaces to check for
1163 * @return bool
1164 * @since 1.19
1165 */
1166 public function inNamespaces( /* ... */ ) {
1167 $namespaces = func_get_args();
1168 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1169 $namespaces = $namespaces[0];
1170 }
1171
1172 foreach ( $namespaces as $ns ) {
1173 if ( $this->inNamespace( $ns ) ) {
1174 return true;
1175 }
1176 }
1177
1178 return false;
1179 }
1180
1181 /**
1182 * Returns true if the title has the same subject namespace as the
1183 * namespace specified.
1184 * For example this method will take NS_USER and return true if namespace
1185 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1186 * as their subject namespace.
1187 *
1188 * This is MUCH simpler than individually testing for equivalence
1189 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1190 * @since 1.19
1191 * @param int $ns
1192 * @return bool
1193 */
1194 public function hasSubjectNamespace( $ns ) {
1195 return MWNamespace::subjectEquals( $this->mNamespace, $ns );
1196 }
1197
1198 /**
1199 * Is this Title in a namespace which contains content?
1200 * In other words, is this a content page, for the purposes of calculating
1201 * statistics, etc?
1202 *
1203 * @return bool
1204 */
1205 public function isContentPage() {
1206 return MWNamespace::isContent( $this->mNamespace );
1207 }
1208
1209 /**
1210 * Would anybody with sufficient privileges be able to move this page?
1211 * Some pages just aren't movable.
1212 *
1213 * @return bool
1214 */
1215 public function isMovable() {
1216 if ( !MWNamespace::isMovable( $this->mNamespace ) || $this->isExternal() ) {
1217 // Interwiki title or immovable namespace. Hooks don't get to override here
1218 return false;
1219 }
1220
1221 $result = true;
1222 Hooks::run( 'TitleIsMovable', [ $this, &$result ] );
1223 return $result;
1224 }
1225
1226 /**
1227 * Is this the mainpage?
1228 * @note Title::newFromText seems to be sufficiently optimized by the title
1229 * cache that we don't need to over-optimize by doing direct comparisons and
1230 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1231 * ends up reporting something differently than $title->isMainPage();
1232 *
1233 * @since 1.18
1234 * @return bool
1235 */
1236 public function isMainPage() {
1237 return $this->equals( self::newMainPage() );
1238 }
1239
1240 /**
1241 * Is this a subpage?
1242 *
1243 * @return bool
1244 */
1245 public function isSubpage() {
1246 return MWNamespace::hasSubpages( $this->mNamespace )
1247 ? strpos( $this->getText(), '/' ) !== false
1248 : false;
1249 }
1250
1251 /**
1252 * Is this a conversion table for the LanguageConverter?
1253 *
1254 * @return bool
1255 */
1256 public function isConversionTable() {
1257 // @todo ConversionTable should become a separate content model.
1258
1259 return $this->mNamespace == NS_MEDIAWIKI &&
1260 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1261 }
1262
1263 /**
1264 * Does that page contain wikitext, or it is JS, CSS or whatever?
1265 *
1266 * @return bool
1267 */
1268 public function isWikitextPage() {
1269 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT );
1270 }
1271
1272 /**
1273 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1274 * global UI. This is generally true for pages in the MediaWiki namespace having
1275 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1276 *
1277 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1278 * for that!
1279 *
1280 * Note that this method should not return true for pages that contain and show
1281 * "inactive" CSS, JSON, or JS.
1282 *
1283 * @return bool
1284 * @since 1.31
1285 */
1286 public function isSiteConfigPage() {
1287 return (
1288 $this->isSiteCssConfigPage()
1289 || $this->isSiteJsonConfigPage()
1290 || $this->isSiteJsConfigPage()
1291 );
1292 }
1293
1294 /**
1295 * @return bool
1296 * @deprecated Since 1.31; use ::isSiteConfigPage() instead (which also checks for JSON pages)
1297 */
1298 public function isCssOrJsPage() {
1299 wfDeprecated( __METHOD__, '1.31' );
1300 return ( NS_MEDIAWIKI == $this->mNamespace
1301 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1302 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) ) );
1303 }
1304
1305 /**
1306 * Is this a "config" (.css, .json, or .js) sub-page of a user page?
1307 *
1308 * @return bool
1309 * @since 1.31
1310 */
1311 public function isUserConfigPage() {
1312 return (
1313 $this->isUserCssConfigPage()
1314 || $this->isUserJsonConfigPage()
1315 || $this->isUserJsConfigPage()
1316 );
1317 }
1318
1319 /**
1320 * @return bool
1321 * @deprecated Since 1.31; use ::isUserConfigPage() instead (which also checks for JSON pages)
1322 */
1323 public function isCssJsSubpage() {
1324 wfDeprecated( __METHOD__, '1.31' );
1325 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1326 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1327 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) ) );
1328 }
1329
1330 /**
1331 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1332 *
1333 * @return string Containing skin name from .css, .json, or .js subpage title
1334 * @since 1.31
1335 */
1336 public function getSkinFromConfigSubpage() {
1337 $subpage = explode( '/', $this->mTextform );
1338 $subpage = $subpage[count( $subpage ) - 1];
1339 $lastdot = strrpos( $subpage, '.' );
1340 if ( $lastdot === false ) {
1341 return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1342 }
1343 return substr( $subpage, 0, $lastdot );
1344 }
1345
1346 /**
1347 * @deprecated Since 1.31; use ::getSkinFromConfigSubpage() instead
1348 * @return string Containing skin name from .css, .json, or .js subpage title
1349 */
1350 public function getSkinFromCssJsSubpage() {
1351 wfDeprecated( __METHOD__, '1.31' );
1352 return $this->getSkinFromConfigSubpage();
1353 }
1354
1355 /**
1356 * Is this a CSS "config" sub-page of a user page?
1357 *
1358 * @return bool
1359 * @since 1.31
1360 */
1361 public function isUserCssConfigPage() {
1362 return (
1363 NS_USER == $this->mNamespace
1364 && $this->isSubpage()
1365 && $this->hasContentModel( CONTENT_MODEL_CSS )
1366 );
1367 }
1368
1369 /**
1370 * @deprecated Since 1.31; use ::isUserCssConfigPage()
1371 * @return bool
1372 */
1373 public function isCssSubpage() {
1374 wfDeprecated( __METHOD__, '1.31' );
1375 return $this->isUserCssConfigPage();
1376 }
1377
1378 /**
1379 * Is this a JSON "config" sub-page of a user page?
1380 *
1381 * @return bool
1382 * @since 1.31
1383 */
1384 public function isUserJsonConfigPage() {
1385 return (
1386 NS_USER == $this->mNamespace
1387 && $this->isSubpage()
1388 && $this->hasContentModel( CONTENT_MODEL_JSON )
1389 );
1390 }
1391
1392 /**
1393 * Is this a JS "config" sub-page of a user page?
1394 *
1395 * @return bool
1396 * @since 1.31
1397 */
1398 public function isUserJsConfigPage() {
1399 return (
1400 NS_USER == $this->mNamespace
1401 && $this->isSubpage()
1402 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
1403 );
1404 }
1405
1406 /**
1407 * @deprecated Since 1.31; use ::isUserJsConfigPage()
1408 * @return bool
1409 */
1410 public function isJsSubpage() {
1411 wfDeprecated( __METHOD__, '1.31' );
1412 return $this->isUserJsConfigPage();
1413 }
1414
1415 /**
1416 * Is this a sitewide CSS "config" page?
1417 *
1418 * @return bool
1419 * @since 1.32
1420 */
1421 public function isSiteCssConfigPage() {
1422 return (
1423 NS_MEDIAWIKI == $this->mNamespace
1424 && (
1425 $this->hasContentModel( CONTENT_MODEL_CSS )
1426 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1427 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1428 || substr( $this->mDbkeyform, -4 ) === '.css'
1429 )
1430 );
1431 }
1432
1433 /**
1434 * Is this a sitewide JSON "config" page?
1435 *
1436 * @return bool
1437 * @since 1.32
1438 */
1439 public function isSiteJsonConfigPage() {
1440 return (
1441 NS_MEDIAWIKI == $this->mNamespace
1442 && (
1443 $this->hasContentModel( CONTENT_MODEL_JSON )
1444 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1445 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1446 || substr( $this->mDbkeyform, -5 ) === '.json'
1447 )
1448 );
1449 }
1450
1451 /**
1452 * Is this a sitewide JS "config" page?
1453 *
1454 * @return bool
1455 * @since 1.31
1456 */
1457 public function isSiteJsConfigPage() {
1458 return (
1459 NS_MEDIAWIKI == $this->mNamespace
1460 && (
1461 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT )
1462 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1463 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1464 || substr( $this->mDbkeyform, -3 ) === '.js'
1465 )
1466 );
1467 }
1468
1469 /**
1470 * Is this a message which can contain raw HTML?
1471 *
1472 * @return bool
1473 * @since 1.32
1474 */
1475 public function isRawHtmlMessage() {
1476 global $wgRawHtmlMessages;
1477
1478 if ( !$this->inNamespace( NS_MEDIAWIKI ) ) {
1479 return false;
1480 }
1481 $message = lcfirst( $this->getRootTitle()->getDBkey() );
1482 return in_array( $message, $wgRawHtmlMessages, true );
1483 }
1484
1485 /**
1486 * Is this a talk page of some sort?
1487 *
1488 * @return bool
1489 */
1490 public function isTalkPage() {
1491 return MWNamespace::isTalk( $this->mNamespace );
1492 }
1493
1494 /**
1495 * Get a Title object associated with the talk page of this article
1496 *
1497 * @return Title The object for the talk page
1498 */
1499 public function getTalkPage() {
1500 return self::makeTitle( MWNamespace::getTalk( $this->mNamespace ), $this->mDbkeyform );
1501 }
1502
1503 /**
1504 * Get a Title object associated with the talk page of this article,
1505 * if such a talk page can exist.
1506 *
1507 * @since 1.30
1508 *
1509 * @return Title|null The object for the talk page,
1510 * or null if no associated talk page can exist, according to canHaveTalkPage().
1511 */
1512 public function getTalkPageIfDefined() {
1513 if ( !$this->canHaveTalkPage() ) {
1514 return null;
1515 }
1516
1517 return $this->getTalkPage();
1518 }
1519
1520 /**
1521 * Get a title object associated with the subject page of this
1522 * talk page
1523 *
1524 * @return Title The object for the subject page
1525 */
1526 public function getSubjectPage() {
1527 // Is this the same title?
1528 $subjectNS = MWNamespace::getSubject( $this->mNamespace );
1529 if ( $this->mNamespace == $subjectNS ) {
1530 return $this;
1531 }
1532 return self::makeTitle( $subjectNS, $this->mDbkeyform );
1533 }
1534
1535 /**
1536 * Get the other title for this page, if this is a subject page
1537 * get the talk page, if it is a subject page get the talk page
1538 *
1539 * @since 1.25
1540 * @throws MWException If the page doesn't have an other page
1541 * @return Title
1542 */
1543 public function getOtherPage() {
1544 if ( $this->isSpecialPage() ) {
1545 throw new MWException( 'Special pages cannot have other pages' );
1546 }
1547 if ( $this->isTalkPage() ) {
1548 return $this->getSubjectPage();
1549 } else {
1550 if ( !$this->canHaveTalkPage() ) {
1551 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1552 }
1553 return $this->getTalkPage();
1554 }
1555 }
1556
1557 /**
1558 * Get the default namespace index, for when there is no namespace
1559 *
1560 * @return int Default namespace index
1561 */
1562 public function getDefaultNamespace() {
1563 return $this->mDefaultNamespace;
1564 }
1565
1566 /**
1567 * Get the Title fragment (i.e.\ the bit after the #) in text form
1568 *
1569 * Use Title::hasFragment to check for a fragment
1570 *
1571 * @return string Title fragment
1572 */
1573 public function getFragment() {
1574 return $this->mFragment;
1575 }
1576
1577 /**
1578 * Check if a Title fragment is set
1579 *
1580 * @return bool
1581 * @since 1.23
1582 */
1583 public function hasFragment() {
1584 return $this->mFragment !== '';
1585 }
1586
1587 /**
1588 * Get the fragment in URL form, including the "#" character if there is one
1589 *
1590 * @return string Fragment in URL form
1591 */
1592 public function getFragmentForURL() {
1593 if ( !$this->hasFragment() ) {
1594 return '';
1595 } elseif ( $this->isExternal() ) {
1596 // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki,
1597 // so we treat it like a local interwiki.
1598 $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
1599 if ( $interwiki && !$interwiki->isLocal() ) {
1600 return '#' . Sanitizer::escapeIdForExternalInterwiki( $this->mFragment );
1601 }
1602 }
1603
1604 return '#' . Sanitizer::escapeIdForLink( $this->mFragment );
1605 }
1606
1607 /**
1608 * Set the fragment for this title. Removes the first character from the
1609 * specified fragment before setting, so it assumes you're passing it with
1610 * an initial "#".
1611 *
1612 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1613 * or Title::createFragmentTarget().
1614 * Still in active use privately.
1615 *
1616 * @private
1617 * @param string $fragment Text
1618 */
1619 public function setFragment( $fragment ) {
1620 $this->mFragment = strtr( substr( $fragment, 1 ), '_', ' ' );
1621 }
1622
1623 /**
1624 * Creates a new Title for a different fragment of the same page.
1625 *
1626 * @since 1.27
1627 * @param string $fragment
1628 * @return Title
1629 */
1630 public function createFragmentTarget( $fragment ) {
1631 return self::makeTitle(
1632 $this->mNamespace,
1633 $this->getText(),
1634 $fragment,
1635 $this->mInterwiki
1636 );
1637 }
1638
1639 /**
1640 * Prefix some arbitrary text with the namespace or interwiki prefix
1641 * of this object
1642 *
1643 * @param string $name The text
1644 * @return string The prefixed text
1645 */
1646 private function prefix( $name ) {
1647 $p = '';
1648 if ( $this->isExternal() ) {
1649 $p = $this->mInterwiki . ':';
1650 }
1651
1652 if ( $this->mNamespace != 0 ) {
1653 $nsText = $this->getNsText();
1654
1655 if ( $nsText === false ) {
1656 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1657 $nsText = MediaWikiServices::getInstance()->getContentLanguage()->
1658 getNsText( NS_SPECIAL ) . ":Badtitle/NS{$this->mNamespace}";
1659 }
1660
1661 $p .= $nsText . ':';
1662 }
1663 return $p . $name;
1664 }
1665
1666 /**
1667 * Get the prefixed database key form
1668 *
1669 * @return string The prefixed title, with underscores and
1670 * any interwiki and namespace prefixes
1671 */
1672 public function getPrefixedDBkey() {
1673 $s = $this->prefix( $this->mDbkeyform );
1674 $s = strtr( $s, ' ', '_' );
1675 return $s;
1676 }
1677
1678 /**
1679 * Get the prefixed title with spaces.
1680 * This is the form usually used for display
1681 *
1682 * @return string The prefixed title, with spaces
1683 */
1684 public function getPrefixedText() {
1685 if ( $this->prefixedText === null ) {
1686 $s = $this->prefix( $this->mTextform );
1687 $s = strtr( $s, '_', ' ' );
1688 $this->prefixedText = $s;
1689 }
1690 return $this->prefixedText;
1691 }
1692
1693 /**
1694 * Return a string representation of this title
1695 *
1696 * @return string Representation of this title
1697 */
1698 public function __toString() {
1699 return $this->getPrefixedText();
1700 }
1701
1702 /**
1703 * Get the prefixed title with spaces, plus any fragment
1704 * (part beginning with '#')
1705 *
1706 * @return string The prefixed title, with spaces and the fragment, including '#'
1707 */
1708 public function getFullText() {
1709 $text = $this->getPrefixedText();
1710 if ( $this->hasFragment() ) {
1711 $text .= '#' . $this->mFragment;
1712 }
1713 return $text;
1714 }
1715
1716 /**
1717 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1718 *
1719 * @par Example:
1720 * @code
1721 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1722 * # returns: 'Foo'
1723 * @endcode
1724 *
1725 * @return string Root name
1726 * @since 1.20
1727 */
1728 public function getRootText() {
1729 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1730 return $this->getText();
1731 }
1732
1733 return strtok( $this->getText(), '/' );
1734 }
1735
1736 /**
1737 * Get the root page name title, i.e. the leftmost part before any slashes
1738 *
1739 * @par Example:
1740 * @code
1741 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1742 * # returns: Title{User:Foo}
1743 * @endcode
1744 *
1745 * @return Title Root title
1746 * @since 1.20
1747 */
1748 public function getRootTitle() {
1749 return self::makeTitle( $this->mNamespace, $this->getRootText() );
1750 }
1751
1752 /**
1753 * Get the base page name without a namespace, i.e. the part before the subpage name
1754 *
1755 * @par Example:
1756 * @code
1757 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1758 * # returns: 'Foo/Bar'
1759 * @endcode
1760 *
1761 * @return string Base name
1762 */
1763 public function getBaseText() {
1764 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1765 return $this->getText();
1766 }
1767
1768 $parts = explode( '/', $this->getText() );
1769 # Don't discard the real title if there's no subpage involved
1770 if ( count( $parts ) > 1 ) {
1771 unset( $parts[count( $parts ) - 1] );
1772 }
1773 return implode( '/', $parts );
1774 }
1775
1776 /**
1777 * Get the base page name title, i.e. the part before the subpage name
1778 *
1779 * @par Example:
1780 * @code
1781 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1782 * # returns: Title{User:Foo/Bar}
1783 * @endcode
1784 *
1785 * @return Title Base title
1786 * @since 1.20
1787 */
1788 public function getBaseTitle() {
1789 return self::makeTitle( $this->mNamespace, $this->getBaseText() );
1790 }
1791
1792 /**
1793 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1794 *
1795 * @par Example:
1796 * @code
1797 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1798 * # returns: "Baz"
1799 * @endcode
1800 *
1801 * @return string Subpage name
1802 */
1803 public function getSubpageText() {
1804 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1805 return $this->mTextform;
1806 }
1807 $parts = explode( '/', $this->mTextform );
1808 return $parts[count( $parts ) - 1];
1809 }
1810
1811 /**
1812 * Get the title for a subpage of the current page
1813 *
1814 * @par Example:
1815 * @code
1816 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1817 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1818 * @endcode
1819 *
1820 * @param string $text The subpage name to add to the title
1821 * @return Title|null Subpage title, or null on an error
1822 * @since 1.20
1823 */
1824 public function getSubpage( $text ) {
1825 return self::makeTitleSafe( $this->mNamespace, $this->getText() . '/' . $text );
1826 }
1827
1828 /**
1829 * Get a URL-encoded form of the subpage text
1830 *
1831 * @return string URL-encoded subpage name
1832 */
1833 public function getSubpageUrlForm() {
1834 $text = $this->getSubpageText();
1835 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1836 return $text;
1837 }
1838
1839 /**
1840 * Get a URL-encoded title (not an actual URL) including interwiki
1841 *
1842 * @return string The URL-encoded form
1843 */
1844 public function getPrefixedURL() {
1845 $s = $this->prefix( $this->mDbkeyform );
1846 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1847 return $s;
1848 }
1849
1850 /**
1851 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1852 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1853 * second argument named variant. This was deprecated in favor
1854 * of passing an array of option with a "variant" key
1855 * Once $query2 is removed for good, this helper can be dropped
1856 * and the wfArrayToCgi moved to getLocalURL();
1857 *
1858 * @since 1.19 (r105919)
1859 * @param array|string $query
1860 * @param string|string[]|bool $query2
1861 * @return string
1862 */
1863 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1864 if ( $query2 !== false ) {
1865 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1866 "method called with a second parameter is deprecated. Add your " .
1867 "parameter to an array passed as the first parameter.", "1.19" );
1868 }
1869 if ( is_array( $query ) ) {
1870 $query = wfArrayToCgi( $query );
1871 }
1872 if ( $query2 ) {
1873 if ( is_string( $query2 ) ) {
1874 // $query2 is a string, we will consider this to be
1875 // a deprecated $variant argument and add it to the query
1876 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1877 } else {
1878 $query2 = wfArrayToCgi( $query2 );
1879 }
1880 // If we have $query content add a & to it first
1881 if ( $query ) {
1882 $query .= '&';
1883 }
1884 // Now append the queries together
1885 $query .= $query2;
1886 }
1887 return $query;
1888 }
1889
1890 /**
1891 * Get a real URL referring to this title, with interwiki link and
1892 * fragment
1893 *
1894 * @see self::getLocalURL for the arguments.
1895 * @see wfExpandUrl
1896 * @param string|string[] $query
1897 * @param string|string[]|bool $query2
1898 * @param string|int|null $proto Protocol type to use in URL
1899 * @return string The URL
1900 */
1901 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1902 $query = self::fixUrlQueryArgs( $query, $query2 );
1903
1904 # Hand off all the decisions on urls to getLocalURL
1905 $url = $this->getLocalURL( $query );
1906
1907 # Expand the url to make it a full url. Note that getLocalURL has the
1908 # potential to output full urls for a variety of reasons, so we use
1909 # wfExpandUrl instead of simply prepending $wgServer
1910 $url = wfExpandUrl( $url, $proto );
1911
1912 # Finally, add the fragment.
1913 $url .= $this->getFragmentForURL();
1914 // Avoid PHP 7.1 warning from passing $this by reference
1915 $titleRef = $this;
1916 Hooks::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1917 return $url;
1918 }
1919
1920 /**
1921 * Get a url appropriate for making redirects based on an untrusted url arg
1922 *
1923 * This is basically the same as getFullUrl(), but in the case of external
1924 * interwikis, we send the user to a landing page, to prevent possible
1925 * phishing attacks and the like.
1926 *
1927 * @note Uses current protocol by default, since technically relative urls
1928 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1929 * places where the url gets cached, as might pollute between
1930 * https and non-https users.
1931 * @see self::getLocalURL for the arguments.
1932 * @param array|string $query
1933 * @param string $proto Protocol type to use in URL
1934 * @return string A url suitable to use in an HTTP location header.
1935 */
1936 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT ) {
1937 $target = $this;
1938 if ( $this->isExternal() ) {
1939 $target = SpecialPage::getTitleFor(
1940 'GoToInterwiki',
1941 $this->getPrefixedDBkey()
1942 );
1943 }
1944 return $target->getFullURL( $query, false, $proto );
1945 }
1946
1947 /**
1948 * Get a URL with no fragment or server name (relative URL) from a Title object.
1949 * If this page is generated with action=render, however,
1950 * $wgServer is prepended to make an absolute URL.
1951 *
1952 * @see self::getFullURL to always get an absolute URL.
1953 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1954 * valid to link, locally, to the current Title.
1955 * @see self::newFromText to produce a Title object.
1956 *
1957 * @param string|string[] $query An optional query string,
1958 * not used for interwiki links. Can be specified as an associative array as well,
1959 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1960 * Some query patterns will trigger various shorturl path replacements.
1961 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1962 * be an array. If a string is passed it will be interpreted as a deprecated
1963 * variant argument and urlencoded into a variant= argument.
1964 * This second query argument will be added to the $query
1965 * The second parameter is deprecated since 1.19. Pass it as a key,value
1966 * pair in the first parameter array instead.
1967 *
1968 * @return string String of the URL.
1969 */
1970 public function getLocalURL( $query = '', $query2 = false ) {
1971 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1972
1973 $query = self::fixUrlQueryArgs( $query, $query2 );
1974
1975 $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
1976 if ( $interwiki ) {
1977 $namespace = $this->getNsText();
1978 if ( $namespace != '' ) {
1979 # Can this actually happen? Interwikis shouldn't be parsed.
1980 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1981 $namespace .= ':';
1982 }
1983 $url = $interwiki->getURL( $namespace . $this->mDbkeyform );
1984 $url = wfAppendQuery( $url, $query );
1985 } else {
1986 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1987 if ( $query == '' ) {
1988 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1989 // Avoid PHP 7.1 warning from passing $this by reference
1990 $titleRef = $this;
1991 Hooks::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1992 } else {
1993 global $wgVariantArticlePath, $wgActionPaths;
1994 $url = false;
1995 $matches = [];
1996
1997 if ( !empty( $wgActionPaths )
1998 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1999 ) {
2000 $action = urldecode( $matches[2] );
2001 if ( isset( $wgActionPaths[$action] ) ) {
2002 $query = $matches[1];
2003 if ( isset( $matches[4] ) ) {
2004 $query .= $matches[4];
2005 }
2006 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
2007 if ( $query != '' ) {
2008 $url = wfAppendQuery( $url, $query );
2009 }
2010 }
2011 }
2012
2013 if ( $url === false
2014 && $wgVariantArticlePath
2015 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2016 && $this->getPageLanguage()->equals(
2017 MediaWikiServices::getInstance()->getContentLanguage() )
2018 && $this->getPageLanguage()->hasVariants()
2019 ) {
2020 $variant = urldecode( $matches[1] );
2021 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
2022 // Only do the variant replacement if the given variant is a valid
2023 // variant for the page's language.
2024 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2025 $url = str_replace( '$1', $dbkey, $url );
2026 }
2027 }
2028
2029 if ( $url === false ) {
2030 if ( $query == '-' ) {
2031 $query = '';
2032 }
2033 $url = "{$wgScript}?title={$dbkey}&{$query}";
2034 }
2035 }
2036 // Avoid PHP 7.1 warning from passing $this by reference
2037 $titleRef = $this;
2038 Hooks::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
2039
2040 // @todo FIXME: This causes breakage in various places when we
2041 // actually expected a local URL and end up with dupe prefixes.
2042 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2043 $url = $wgServer . $url;
2044 }
2045 }
2046 // Avoid PHP 7.1 warning from passing $this by reference
2047 $titleRef = $this;
2048 Hooks::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
2049 return $url;
2050 }
2051
2052 /**
2053 * Get a URL that's the simplest URL that will be valid to link, locally,
2054 * to the current Title. It includes the fragment, but does not include
2055 * the server unless action=render is used (or the link is external). If
2056 * there's a fragment but the prefixed text is empty, we just return a link
2057 * to the fragment.
2058 *
2059 * The result obviously should not be URL-escaped, but does need to be
2060 * HTML-escaped if it's being output in HTML.
2061 *
2062 * @param string|string[] $query
2063 * @param bool $query2
2064 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2065 * or false (default) for no expansion
2066 * @see self::getLocalURL for the arguments.
2067 * @return string The URL
2068 */
2069 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2070 if ( $this->isExternal() || $proto !== false ) {
2071 $ret = $this->getFullURL( $query, $query2, $proto );
2072 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2073 $ret = $this->getFragmentForURL();
2074 } else {
2075 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2076 }
2077 return $ret;
2078 }
2079
2080 /**
2081 * Get the URL form for an internal link.
2082 * - Used in various CDN-related code, in case we have a different
2083 * internal hostname for the server from the exposed one.
2084 *
2085 * This uses $wgInternalServer to qualify the path, or $wgServer
2086 * if $wgInternalServer is not set. If the server variable used is
2087 * protocol-relative, the URL will be expanded to http://
2088 *
2089 * @see self::getLocalURL for the arguments.
2090 * @param string $query
2091 * @param string|bool $query2
2092 * @return string The URL
2093 */
2094 public function getInternalURL( $query = '', $query2 = false ) {
2095 global $wgInternalServer, $wgServer;
2096 $query = self::fixUrlQueryArgs( $query, $query2 );
2097 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
2098 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
2099 // Avoid PHP 7.1 warning from passing $this by reference
2100 $titleRef = $this;
2101 Hooks::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2102 return $url;
2103 }
2104
2105 /**
2106 * Get the URL for a canonical link, for use in things like IRC and
2107 * e-mail notifications. Uses $wgCanonicalServer and the
2108 * GetCanonicalURL hook.
2109 *
2110 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2111 *
2112 * @see self::getLocalURL for the arguments.
2113 * @param string $query
2114 * @param string|bool $query2
2115 * @return string The URL
2116 * @since 1.18
2117 */
2118 public function getCanonicalURL( $query = '', $query2 = false ) {
2119 $query = self::fixUrlQueryArgs( $query, $query2 );
2120 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
2121 // Avoid PHP 7.1 warning from passing $this by reference
2122 $titleRef = $this;
2123 Hooks::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2124 return $url;
2125 }
2126
2127 /**
2128 * Get the edit URL for this Title
2129 *
2130 * @return string The URL, or a null string if this is an interwiki link
2131 */
2132 public function getEditURL() {
2133 if ( $this->isExternal() ) {
2134 return '';
2135 }
2136 $s = $this->getLocalURL( 'action=edit' );
2137
2138 return $s;
2139 }
2140
2141 /**
2142 * Can $user perform $action on this page?
2143 * This skips potentially expensive cascading permission checks
2144 * as well as avoids expensive error formatting
2145 *
2146 * Suitable for use for nonessential UI controls in common cases, but
2147 * _not_ for functional access control.
2148 *
2149 * May provide false positives, but should never provide a false negative.
2150 *
2151 * @param string $action Action that permission needs to be checked for
2152 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2153 * @return bool
2154 */
2155 public function quickUserCan( $action, $user = null ) {
2156 return $this->userCan( $action, $user, false );
2157 }
2158
2159 /**
2160 * Can $user perform $action on this page?
2161 *
2162 * @param string $action Action that permission needs to be checked for
2163 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2164 * provided.
2165 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2166 * @return bool
2167 */
2168 public function userCan( $action, $user = null, $rigor = 'secure' ) {
2169 if ( !$user instanceof User ) {
2170 global $wgUser;
2171 $user = $wgUser;
2172 }
2173
2174 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
2175 }
2176
2177 /**
2178 * Can $user perform $action on this page?
2179 *
2180 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2181 *
2182 * @param string $action Action that permission needs to be checked for
2183 * @param User $user User to check
2184 * @param string $rigor One of (quick,full,secure)
2185 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2186 * - full : does cheap and expensive checks possibly from a replica DB
2187 * - secure : does cheap and expensive checks, using the master as needed
2188 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2189 * whose corresponding errors may be ignored.
2190 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2191 */
2192 public function getUserPermissionsErrors(
2193 $action, $user, $rigor = 'secure', $ignoreErrors = []
2194 ) {
2195 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
2196
2197 // Remove the errors being ignored.
2198 foreach ( $errors as $index => $error ) {
2199 $errKey = is_array( $error ) ? $error[0] : $error;
2200
2201 if ( in_array( $errKey, $ignoreErrors ) ) {
2202 unset( $errors[$index] );
2203 }
2204 if ( $errKey instanceof MessageSpecifier && in_array( $errKey->getKey(), $ignoreErrors ) ) {
2205 unset( $errors[$index] );
2206 }
2207 }
2208
2209 return $errors;
2210 }
2211
2212 /**
2213 * Permissions checks that fail most often, and which are easiest to test.
2214 *
2215 * @param string $action The action to check
2216 * @param User $user User to check
2217 * @param array $errors List of current errors
2218 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2219 * @param bool $short Short circuit on first error
2220 *
2221 * @return array List of errors
2222 */
2223 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
2224 if ( !Hooks::run( 'TitleQuickPermissions',
2225 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
2226 ) {
2227 return $errors;
2228 }
2229
2230 if ( $action == 'create' ) {
2231 if (
2232 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
2233 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
2234 ) {
2235 $errors[] = $user->isAnon() ? [ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
2236 }
2237 } elseif ( $action == 'move' ) {
2238 if ( !$user->isAllowed( 'move-rootuserpages' )
2239 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
2240 // Show user page-specific message only if the user can move other pages
2241 $errors[] = [ 'cant-move-user-page' ];
2242 }
2243
2244 // Check if user is allowed to move files if it's a file
2245 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
2246 $errors[] = [ 'movenotallowedfile' ];
2247 }
2248
2249 // Check if user is allowed to move category pages if it's a category page
2250 if ( $this->mNamespace == NS_CATEGORY && !$user->isAllowed( 'move-categorypages' ) ) {
2251 $errors[] = [ 'cant-move-category-page' ];
2252 }
2253
2254 if ( !$user->isAllowed( 'move' ) ) {
2255 // User can't move anything
2256 $userCanMove = User::groupHasPermission( 'user', 'move' );
2257 $autoconfirmedCanMove = User::groupHasPermission( 'autoconfirmed', 'move' );
2258 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
2259 // custom message if logged-in users without any special rights can move
2260 $errors[] = [ 'movenologintext' ];
2261 } else {
2262 $errors[] = [ 'movenotallowed' ];
2263 }
2264 }
2265 } elseif ( $action == 'move-target' ) {
2266 if ( !$user->isAllowed( 'move' ) ) {
2267 // User can't move anything
2268 $errors[] = [ 'movenotallowed' ];
2269 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2270 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
2271 // Show user page-specific message only if the user can move other pages
2272 $errors[] = [ 'cant-move-to-user-page' ];
2273 } elseif ( !$user->isAllowed( 'move-categorypages' )
2274 && $this->mNamespace == NS_CATEGORY ) {
2275 // Show category page-specific message only if the user can move other pages
2276 $errors[] = [ 'cant-move-to-category-page' ];
2277 }
2278 } elseif ( !$user->isAllowed( $action ) ) {
2279 $errors[] = $this->missingPermissionError( $action, $short );
2280 }
2281
2282 return $errors;
2283 }
2284
2285 /**
2286 * Add the resulting error code to the errors array
2287 *
2288 * @param array $errors List of current errors
2289 * @param array $result Result of errors
2290 *
2291 * @return array List of errors
2292 */
2293 private function resultToError( $errors, $result ) {
2294 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2295 // A single array representing an error
2296 $errors[] = $result;
2297 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2298 // A nested array representing multiple errors
2299 $errors = array_merge( $errors, $result );
2300 } elseif ( $result !== '' && is_string( $result ) ) {
2301 // A string representing a message-id
2302 $errors[] = [ $result ];
2303 } elseif ( $result instanceof MessageSpecifier ) {
2304 // A message specifier representing an error
2305 $errors[] = [ $result ];
2306 } elseif ( $result === false ) {
2307 // a generic "We don't want them to do that"
2308 $errors[] = [ 'badaccess-group0' ];
2309 }
2310 return $errors;
2311 }
2312
2313 /**
2314 * Check various permission hooks
2315 *
2316 * @param string $action The action to check
2317 * @param User $user User to check
2318 * @param array $errors List of current errors
2319 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2320 * @param bool $short Short circuit on first error
2321 *
2322 * @return array List of errors
2323 */
2324 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2325 // Use getUserPermissionsErrors instead
2326 $result = '';
2327 // Avoid PHP 7.1 warning from passing $this by reference
2328 $titleRef = $this;
2329 if ( !Hooks::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2330 return $result ? [] : [ [ 'badaccess-group0' ] ];
2331 }
2332 // Check getUserPermissionsErrors hook
2333 // Avoid PHP 7.1 warning from passing $this by reference
2334 $titleRef = $this;
2335 if ( !Hooks::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2336 $errors = $this->resultToError( $errors, $result );
2337 }
2338 // Check getUserPermissionsErrorsExpensive hook
2339 if (
2340 $rigor !== 'quick'
2341 && !( $short && count( $errors ) > 0 )
2342 && !Hooks::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2343 ) {
2344 $errors = $this->resultToError( $errors, $result );
2345 }
2346
2347 return $errors;
2348 }
2349
2350 /**
2351 * Check permissions on special pages & namespaces
2352 *
2353 * @param string $action The action to check
2354 * @param User $user User to check
2355 * @param array $errors List of current errors
2356 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2357 * @param bool $short Short circuit on first error
2358 *
2359 * @return array List of errors
2360 */
2361 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2362 # Only 'createaccount' can be performed on special pages,
2363 # which don't actually exist in the DB.
2364 if ( $this->isSpecialPage() && $action !== 'createaccount' ) {
2365 $errors[] = [ 'ns-specialprotected' ];
2366 }
2367
2368 # Check $wgNamespaceProtection for restricted namespaces
2369 if ( $this->isNamespaceProtected( $user ) ) {
2370 $ns = $this->mNamespace == NS_MAIN ?
2371 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2372 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
2373 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2374 }
2375
2376 return $errors;
2377 }
2378
2379 /**
2380 * Check sitewide CSS/JSON/JS permissions
2381 *
2382 * @param string $action The action to check
2383 * @param User $user User to check
2384 * @param array $errors List of current errors
2385 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2386 * @param bool $short Short circuit on first error
2387 *
2388 * @return array List of errors
2389 */
2390 private function checkSiteConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2391 if ( $action != 'patrol' ) {
2392 $error = null;
2393 // Sitewide CSS/JSON/JS changes, like all NS_MEDIAWIKI changes, also require the
2394 // editinterface right. That's implemented as a restriction so no check needed here.
2395 if ( $this->isSiteCssConfigPage() && !$user->isAllowed( 'editsitecss' ) ) {
2396 $error = [ 'sitecssprotected', $action ];
2397 } elseif ( $this->isSiteJsonConfigPage() && !$user->isAllowed( 'editsitejson' ) ) {
2398 $error = [ 'sitejsonprotected', $action ];
2399 } elseif ( $this->isSiteJsConfigPage() && !$user->isAllowed( 'editsitejs' ) ) {
2400 $error = [ 'sitejsprotected', $action ];
2401 } elseif ( $this->isRawHtmlMessage() ) {
2402 // Raw HTML can be used to deploy CSS or JS so require rights for both.
2403 if ( !$user->isAllowed( 'editsitejs' ) ) {
2404 $error = [ 'sitejsprotected', $action ];
2405 } elseif ( !$user->isAllowed( 'editsitecss' ) ) {
2406 $error = [ 'sitecssprotected', $action ];
2407 }
2408 }
2409
2410 if ( $error ) {
2411 if ( $user->isAllowed( 'editinterface' ) ) {
2412 // Most users / site admins will probably find out about the new, more restrictive
2413 // permissions by failing to edit something. Give them more info.
2414 // TODO remove this a few release cycles after 1.32
2415 $error = [ 'interfaceadmin-info', wfMessage( $error[0], $error[1] ) ];
2416 }
2417 $errors[] = $error;
2418 }
2419 }
2420
2421 return $errors;
2422 }
2423
2424 /**
2425 * Check CSS/JSON/JS sub-page permissions
2426 *
2427 * @param string $action The action to check
2428 * @param User $user User to check
2429 * @param array $errors List of current errors
2430 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2431 * @param bool $short Short circuit on first error
2432 *
2433 * @return array List of errors
2434 */
2435 private function checkUserConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2436 # Protect css/json/js subpages of user pages
2437 # XXX: this might be better using restrictions
2438
2439 if ( $action === 'patrol' ) {
2440 return $errors;
2441 }
2442
2443 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
2444 // Users need editmyuser* to edit their own CSS/JSON/JS subpages.
2445 if (
2446 $this->isUserCssConfigPage()
2447 && !$user->isAllowedAny( 'editmyusercss', 'editusercss' )
2448 ) {
2449 $errors[] = [ 'mycustomcssprotected', $action ];
2450 } elseif (
2451 $this->isUserJsonConfigPage()
2452 && !$user->isAllowedAny( 'editmyuserjson', 'edituserjson' )
2453 ) {
2454 $errors[] = [ 'mycustomjsonprotected', $action ];
2455 } elseif (
2456 $this->isUserJsConfigPage()
2457 && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' )
2458 ) {
2459 $errors[] = [ 'mycustomjsprotected', $action ];
2460 }
2461 } else {
2462 // Users need editmyuser* to edit their own CSS/JSON/JS subpages, except for
2463 // deletion/suppression which cannot be used for attacks and we want to avoid the
2464 // situation where an unprivileged user can post abusive content on their subpages
2465 // and only very highly privileged users could remove it.
2466 if ( !in_array( $action, [ 'delete', 'deleterevision', 'suppressrevision' ], true ) ) {
2467 if (
2468 $this->isUserCssConfigPage()
2469 && !$user->isAllowed( 'editusercss' )
2470 ) {
2471 $errors[] = [ 'customcssprotected', $action ];
2472 } elseif (
2473 $this->isUserJsonConfigPage()
2474 && !$user->isAllowed( 'edituserjson' )
2475 ) {
2476 $errors[] = [ 'customjsonprotected', $action ];
2477 } elseif (
2478 $this->isUserJsConfigPage()
2479 && !$user->isAllowed( 'edituserjs' )
2480 ) {
2481 $errors[] = [ 'customjsprotected', $action ];
2482 }
2483 }
2484 }
2485
2486 return $errors;
2487 }
2488
2489 /**
2490 * Check against page_restrictions table requirements on this
2491 * page. The user must possess all required rights for this
2492 * action.
2493 *
2494 * @param string $action The action to check
2495 * @param User $user User to check
2496 * @param array $errors List of current errors
2497 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2498 * @param bool $short Short circuit on first error
2499 *
2500 * @return array List of errors
2501 */
2502 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2503 foreach ( $this->getRestrictions( $action ) as $right ) {
2504 // Backwards compatibility, rewrite sysop -> editprotected
2505 if ( $right == 'sysop' ) {
2506 $right = 'editprotected';
2507 }
2508 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2509 if ( $right == 'autoconfirmed' ) {
2510 $right = 'editsemiprotected';
2511 }
2512 if ( $right == '' ) {
2513 continue;
2514 }
2515 if ( !$user->isAllowed( $right ) ) {
2516 $errors[] = [ 'protectedpagetext', $right, $action ];
2517 } elseif ( $this->mCascadeRestriction && !$user->isAllowed( 'protect' ) ) {
2518 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2519 }
2520 }
2521
2522 return $errors;
2523 }
2524
2525 /**
2526 * Check restrictions on cascading pages.
2527 *
2528 * @param string $action The action to check
2529 * @param User $user User to check
2530 * @param array $errors List of current errors
2531 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2532 * @param bool $short Short circuit on first error
2533 *
2534 * @return array List of errors
2535 */
2536 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2537 if ( $rigor !== 'quick' && !$this->isUserConfigPage() ) {
2538 # We /could/ use the protection level on the source page, but it's
2539 # fairly ugly as we have to establish a precedence hierarchy for pages
2540 # included by multiple cascade-protected pages. So just restrict
2541 # it to people with 'protect' permission, as they could remove the
2542 # protection anyway.
2543 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2544 # Cascading protection depends on more than this page...
2545 # Several cascading protected pages may include this page...
2546 # Check each cascading level
2547 # This is only for protection restrictions, not for all actions
2548 if ( isset( $restrictions[$action] ) ) {
2549 foreach ( $restrictions[$action] as $right ) {
2550 // Backwards compatibility, rewrite sysop -> editprotected
2551 if ( $right == 'sysop' ) {
2552 $right = 'editprotected';
2553 }
2554 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2555 if ( $right == 'autoconfirmed' ) {
2556 $right = 'editsemiprotected';
2557 }
2558 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2559 $pages = '';
2560 foreach ( $cascadingSources as $page ) {
2561 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2562 }
2563 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2564 }
2565 }
2566 }
2567 }
2568
2569 return $errors;
2570 }
2571
2572 /**
2573 * Check action permissions not already checked in checkQuickPermissions
2574 *
2575 * @param string $action The action to check
2576 * @param User $user User to check
2577 * @param array $errors List of current errors
2578 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2579 * @param bool $short Short circuit on first error
2580 *
2581 * @return array List of errors
2582 */
2583 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2584 global $wgDeleteRevisionsLimit, $wgLang;
2585
2586 if ( $action == 'protect' ) {
2587 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2588 // If they can't edit, they shouldn't protect.
2589 $errors[] = [ 'protect-cantedit' ];
2590 }
2591 } elseif ( $action == 'create' ) {
2592 $title_protection = $this->getTitleProtection();
2593 if ( $title_protection ) {
2594 if ( $title_protection['permission'] == ''
2595 || !$user->isAllowed( $title_protection['permission'] )
2596 ) {
2597 $errors[] = [
2598 'titleprotected',
2599 User::whoIs( $title_protection['user'] ),
2600 $title_protection['reason']
2601 ];
2602 }
2603 }
2604 } elseif ( $action == 'move' ) {
2605 // Check for immobile pages
2606 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2607 // Specific message for this case
2608 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2609 } elseif ( !$this->isMovable() ) {
2610 // Less specific message for rarer cases
2611 $errors[] = [ 'immobile-source-page' ];
2612 }
2613 } elseif ( $action == 'move-target' ) {
2614 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2615 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2616 } elseif ( !$this->isMovable() ) {
2617 $errors[] = [ 'immobile-target-page' ];
2618 }
2619 } elseif ( $action == 'delete' ) {
2620 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2621 if ( !$tempErrors ) {
2622 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2623 $user, $tempErrors, $rigor, true );
2624 }
2625 if ( $tempErrors ) {
2626 // If protection keeps them from editing, they shouldn't be able to delete.
2627 $errors[] = [ 'deleteprotected' ];
2628 }
2629 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2630 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2631 ) {
2632 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2633 }
2634 } elseif ( $action === 'undelete' ) {
2635 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2636 // Undeleting implies editing
2637 $errors[] = [ 'undelete-cantedit' ];
2638 }
2639 if ( !$this->exists()
2640 && count( $this->getUserPermissionsErrorsInternal( 'create', $user, $rigor, true ) )
2641 ) {
2642 // Undeleting where nothing currently exists implies creating
2643 $errors[] = [ 'undelete-cantcreate' ];
2644 }
2645 }
2646 return $errors;
2647 }
2648
2649 /**
2650 * Check that the user isn't blocked from editing.
2651 *
2652 * @param string $action The action to check
2653 * @param User $user User to check
2654 * @param array $errors List of current errors
2655 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2656 * @param bool $short Short circuit on first error
2657 *
2658 * @return array List of errors
2659 */
2660 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2661 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2662 // Account creation blocks handled at userlogin.
2663 // Unblocking handled in SpecialUnblock
2664 if ( $rigor === 'quick' || in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2665 return $errors;
2666 }
2667
2668 // Optimize for a very common case
2669 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2670 return $errors;
2671 }
2672
2673 if ( $wgEmailConfirmToEdit
2674 && !$user->isEmailConfirmed()
2675 && $action === 'edit'
2676 ) {
2677 $errors[] = [ 'confirmedittext' ];
2678 }
2679
2680 $useReplica = ( $rigor !== 'secure' );
2681 $block = $user->getBlock( $useReplica );
2682
2683 // The block may explicitly allow an action (like "read" or "upload").
2684 if ( $block && $block->prevents( $action ) === false ) {
2685 return $errors;
2686 }
2687
2688 // Determine if the user is blocked from this action on this page.
2689 // What gets passed into this method is a user right, not an action name.
2690 // There is no way to instantiate an action by restriction. However, this
2691 // will get the action where the restriction is the same. This may result
2692 // in actions being blocked that shouldn't be.
2693 $actionObj = null;
2694 if ( Action::exists( $action ) ) {
2695 // Clone the title to prevent mutations to this object which is done
2696 // by Title::loadFromRow() in WikiPage::loadFromRow().
2697 $page = WikiPage::factory( clone $this );
2698 // Creating an action will perform several database queries to ensure that
2699 // the action has not been overridden by the content type.
2700 // @todo FIXME: Pass the relevant context into this function.
2701 $actionObj = Action::factory( $action, $page, RequestContext::getMain() );
2702 // Ensure that the retrieved action matches the restriction.
2703 if ( $actionObj && $actionObj->getRestriction() !== $action ) {
2704 $actionObj = null;
2705 }
2706 }
2707
2708 // If no action object is returned, assume that the action requires unblock
2709 // which is the default.
2710 if ( !$actionObj || $actionObj->requiresUnblock() ) {
2711 if ( $user->isBlockedFrom( $this, $useReplica ) ) {
2712 // @todo FIXME: Pass the relevant context into this function.
2713 $errors[] = $block
2714 ? $block->getPermissionsError( RequestContext::getMain() )
2715 : [ 'actionblockedtext' ];
2716 }
2717 }
2718
2719 return $errors;
2720 }
2721
2722 /**
2723 * Check that the user is allowed to read this page.
2724 *
2725 * @param string $action The action to check
2726 * @param User $user User to check
2727 * @param array $errors List of current errors
2728 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2729 * @param bool $short Short circuit on first error
2730 *
2731 * @return array List of errors
2732 */
2733 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2734 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2735
2736 $whitelisted = false;
2737 if ( User::isEveryoneAllowed( 'read' ) ) {
2738 # Shortcut for public wikis, allows skipping quite a bit of code
2739 $whitelisted = true;
2740 } elseif ( $user->isAllowed( 'read' ) ) {
2741 # If the user is allowed to read pages, he is allowed to read all pages
2742 $whitelisted = true;
2743 } elseif ( $this->isSpecial( 'Userlogin' )
2744 || $this->isSpecial( 'PasswordReset' )
2745 || $this->isSpecial( 'Userlogout' )
2746 ) {
2747 # Always grant access to the login page.
2748 # Even anons need to be able to log in.
2749 $whitelisted = true;
2750 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2751 # Time to check the whitelist
2752 # Only do these checks is there's something to check against
2753 $name = $this->getPrefixedText();
2754 $dbName = $this->getPrefixedDBkey();
2755
2756 // Check for explicit whitelisting with and without underscores
2757 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) ) {
2758 $whitelisted = true;
2759 } elseif ( $this->mNamespace == NS_MAIN ) {
2760 # Old settings might have the title prefixed with
2761 # a colon for main-namespace pages
2762 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2763 $whitelisted = true;
2764 }
2765 } elseif ( $this->isSpecialPage() ) {
2766 # If it's a special page, ditch the subpage bit and check again
2767 $name = $this->mDbkeyform;
2768 list( $name, /* $subpage */ ) =
2769 MediaWikiServices::getInstance()->getSpecialPageFactory()->
2770 resolveAlias( $name );
2771 if ( $name ) {
2772 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
2773 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2774 $whitelisted = true;
2775 }
2776 }
2777 }
2778 }
2779
2780 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2781 $name = $this->getPrefixedText();
2782 // Check for regex whitelisting
2783 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2784 if ( preg_match( $listItem, $name ) ) {
2785 $whitelisted = true;
2786 break;
2787 }
2788 }
2789 }
2790
2791 if ( !$whitelisted ) {
2792 # If the title is not whitelisted, give extensions a chance to do so...
2793 Hooks::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2794 if ( !$whitelisted ) {
2795 $errors[] = $this->missingPermissionError( $action, $short );
2796 }
2797 }
2798
2799 return $errors;
2800 }
2801
2802 /**
2803 * Get a description array when the user doesn't have the right to perform
2804 * $action (i.e. when User::isAllowed() returns false)
2805 *
2806 * @param string $action The action to check
2807 * @param bool $short Short circuit on first error
2808 * @return array Array containing an error message key and any parameters
2809 */
2810 private function missingPermissionError( $action, $short ) {
2811 // We avoid expensive display logic for quickUserCan's and such
2812 if ( $short ) {
2813 return [ 'badaccess-group0' ];
2814 }
2815
2816 return User::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2817 }
2818
2819 /**
2820 * Can $user perform $action on this page? This is an internal function,
2821 * with multiple levels of checks depending on performance needs; see $rigor below.
2822 * It does not check wfReadOnly().
2823 *
2824 * @param string $action Action that permission needs to be checked for
2825 * @param User $user User to check
2826 * @param string $rigor One of (quick,full,secure)
2827 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2828 * - full : does cheap and expensive checks possibly from a replica DB
2829 * - secure : does cheap and expensive checks, using the master as needed
2830 * @param bool $short Set this to true to stop after the first permission error.
2831 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2832 */
2833 protected function getUserPermissionsErrorsInternal(
2834 $action, $user, $rigor = 'secure', $short = false
2835 ) {
2836 if ( $rigor === true ) {
2837 $rigor = 'secure'; // b/c
2838 } elseif ( $rigor === false ) {
2839 $rigor = 'quick'; // b/c
2840 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2841 throw new Exception( "Invalid rigor parameter '$rigor'." );
2842 }
2843
2844 # Read has special handling
2845 if ( $action == 'read' ) {
2846 $checks = [
2847 'checkPermissionHooks',
2848 'checkReadPermissions',
2849 'checkUserBlock', // for wgBlockDisablesLogin
2850 ];
2851 # Don't call checkSpecialsAndNSPermissions, checkSiteConfigPermissions
2852 # or checkUserConfigPermissions here as it will lead to duplicate
2853 # error messages. This is okay to do since anywhere that checks for
2854 # create will also check for edit, and those checks are called for edit.
2855 } elseif ( $action == 'create' ) {
2856 $checks = [
2857 'checkQuickPermissions',
2858 'checkPermissionHooks',
2859 'checkPageRestrictions',
2860 'checkCascadingSourcesRestrictions',
2861 'checkActionPermissions',
2862 'checkUserBlock'
2863 ];
2864 } else {
2865 $checks = [
2866 'checkQuickPermissions',
2867 'checkPermissionHooks',
2868 'checkSpecialsAndNSPermissions',
2869 'checkSiteConfigPermissions',
2870 'checkUserConfigPermissions',
2871 'checkPageRestrictions',
2872 'checkCascadingSourcesRestrictions',
2873 'checkActionPermissions',
2874 'checkUserBlock'
2875 ];
2876 }
2877
2878 $errors = [];
2879 foreach ( $checks as $method ) {
2880 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2881
2882 if ( $short && $errors !== [] ) {
2883 break;
2884 }
2885 }
2886
2887 return $errors;
2888 }
2889
2890 /**
2891 * Get a filtered list of all restriction types supported by this wiki.
2892 * @param bool $exists True to get all restriction types that apply to
2893 * titles that do exist, False for all restriction types that apply to
2894 * titles that do not exist
2895 * @return array
2896 */
2897 public static function getFilteredRestrictionTypes( $exists = true ) {
2898 global $wgRestrictionTypes;
2899 $types = $wgRestrictionTypes;
2900 if ( $exists ) {
2901 # Remove the create restriction for existing titles
2902 $types = array_diff( $types, [ 'create' ] );
2903 } else {
2904 # Only the create and upload restrictions apply to non-existing titles
2905 $types = array_intersect( $types, [ 'create', 'upload' ] );
2906 }
2907 return $types;
2908 }
2909
2910 /**
2911 * Returns restriction types for the current Title
2912 *
2913 * @return array Applicable restriction types
2914 */
2915 public function getRestrictionTypes() {
2916 if ( $this->isSpecialPage() ) {
2917 return [];
2918 }
2919
2920 $types = self::getFilteredRestrictionTypes( $this->exists() );
2921
2922 if ( $this->mNamespace != NS_FILE ) {
2923 # Remove the upload restriction for non-file titles
2924 $types = array_diff( $types, [ 'upload' ] );
2925 }
2926
2927 Hooks::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2928
2929 wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2930 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2931
2932 return $types;
2933 }
2934
2935 /**
2936 * Is this title subject to title protection?
2937 * Title protection is the one applied against creation of such title.
2938 *
2939 * @return array|bool An associative array representing any existent title
2940 * protection, or false if there's none.
2941 */
2942 public function getTitleProtection() {
2943 $protection = $this->getTitleProtectionInternal();
2944 if ( $protection ) {
2945 if ( $protection['permission'] == 'sysop' ) {
2946 $protection['permission'] = 'editprotected'; // B/C
2947 }
2948 if ( $protection['permission'] == 'autoconfirmed' ) {
2949 $protection['permission'] = 'editsemiprotected'; // B/C
2950 }
2951 }
2952 return $protection;
2953 }
2954
2955 /**
2956 * Fetch title protection settings
2957 *
2958 * To work correctly, $this->loadRestrictions() needs to have access to the
2959 * actual protections in the database without munging 'sysop' =>
2960 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2961 * callers probably want $this->getTitleProtection() instead.
2962 *
2963 * @return array|bool
2964 */
2965 protected function getTitleProtectionInternal() {
2966 // Can't protect pages in special namespaces
2967 if ( $this->mNamespace < 0 ) {
2968 return false;
2969 }
2970
2971 // Can't protect pages that exist.
2972 if ( $this->exists() ) {
2973 return false;
2974 }
2975
2976 if ( $this->mTitleProtection === null ) {
2977 $dbr = wfGetDB( DB_REPLICA );
2978 $commentStore = CommentStore::getStore();
2979 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2980 $res = $dbr->select(
2981 [ 'protected_titles' ] + $commentQuery['tables'],
2982 [
2983 'user' => 'pt_user',
2984 'expiry' => 'pt_expiry',
2985 'permission' => 'pt_create_perm'
2986 ] + $commentQuery['fields'],
2987 [ 'pt_namespace' => $this->mNamespace, 'pt_title' => $this->mDbkeyform ],
2988 __METHOD__,
2989 [],
2990 $commentQuery['joins']
2991 );
2992
2993 // fetchRow returns false if there are no rows.
2994 $row = $dbr->fetchRow( $res );
2995 if ( $row ) {
2996 $this->mTitleProtection = [
2997 'user' => $row['user'],
2998 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2999 'permission' => $row['permission'],
3000 'reason' => $commentStore->getComment( 'pt_reason', $row )->text,
3001 ];
3002 } else {
3003 $this->mTitleProtection = false;
3004 }
3005 }
3006 return $this->mTitleProtection;
3007 }
3008
3009 /**
3010 * Remove any title protection due to page existing
3011 */
3012 public function deleteTitleProtection() {
3013 $dbw = wfGetDB( DB_MASTER );
3014
3015 $dbw->delete(
3016 'protected_titles',
3017 [ 'pt_namespace' => $this->mNamespace, 'pt_title' => $this->mDbkeyform ],
3018 __METHOD__
3019 );
3020 $this->mTitleProtection = false;
3021 }
3022
3023 /**
3024 * Is this page "semi-protected" - the *only* protection levels are listed
3025 * in $wgSemiprotectedRestrictionLevels?
3026 *
3027 * @param string $action Action to check (default: edit)
3028 * @return bool
3029 */
3030 public function isSemiProtected( $action = 'edit' ) {
3031 global $wgSemiprotectedRestrictionLevels;
3032
3033 $restrictions = $this->getRestrictions( $action );
3034 $semi = $wgSemiprotectedRestrictionLevels;
3035 if ( !$restrictions || !$semi ) {
3036 // Not protected, or all protection is full protection
3037 return false;
3038 }
3039
3040 // Remap autoconfirmed to editsemiprotected for BC
3041 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
3042 $semi[$key] = 'editsemiprotected';
3043 }
3044 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
3045 $restrictions[$key] = 'editsemiprotected';
3046 }
3047
3048 return !array_diff( $restrictions, $semi );
3049 }
3050
3051 /**
3052 * Does the title correspond to a protected article?
3053 *
3054 * @param string $action The action the page is protected from,
3055 * by default checks all actions.
3056 * @return bool
3057 */
3058 public function isProtected( $action = '' ) {
3059 global $wgRestrictionLevels;
3060
3061 $restrictionTypes = $this->getRestrictionTypes();
3062
3063 # Special pages have inherent protection
3064 if ( $this->isSpecialPage() ) {
3065 return true;
3066 }
3067
3068 # Check regular protection levels
3069 foreach ( $restrictionTypes as $type ) {
3070 if ( $action == $type || $action == '' ) {
3071 $r = $this->getRestrictions( $type );
3072 foreach ( $wgRestrictionLevels as $level ) {
3073 if ( in_array( $level, $r ) && $level != '' ) {
3074 return true;
3075 }
3076 }
3077 }
3078 }
3079
3080 return false;
3081 }
3082
3083 /**
3084 * Determines if $user is unable to edit this page because it has been protected
3085 * by $wgNamespaceProtection.
3086 *
3087 * @param User $user User object to check permissions
3088 * @return bool
3089 */
3090 public function isNamespaceProtected( User $user ) {
3091 global $wgNamespaceProtection;
3092
3093 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
3094 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
3095 if ( $right != '' && !$user->isAllowed( $right ) ) {
3096 return true;
3097 }
3098 }
3099 }
3100 return false;
3101 }
3102
3103 /**
3104 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
3105 *
3106 * @return bool If the page is subject to cascading restrictions.
3107 */
3108 public function isCascadeProtected() {
3109 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
3110 return ( $sources > 0 );
3111 }
3112
3113 /**
3114 * Determines whether cascading protection sources have already been loaded from
3115 * the database.
3116 *
3117 * @param bool $getPages True to check if the pages are loaded, or false to check
3118 * if the status is loaded.
3119 * @return bool Whether or not the specified information has been loaded
3120 * @since 1.23
3121 */
3122 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
3123 return $getPages ? $this->mCascadeSources !== null : $this->mHasCascadingRestrictions !== null;
3124 }
3125
3126 /**
3127 * Cascading protection: Get the source of any cascading restrictions on this page.
3128 *
3129 * @param bool $getPages Whether or not to retrieve the actual pages
3130 * that the restrictions have come from and the actual restrictions
3131 * themselves.
3132 * @return array Two elements: First is an array of Title objects of the
3133 * pages from which cascading restrictions have come, false for
3134 * none, or true if such restrictions exist but $getPages was not
3135 * set. Second is an array like that returned by
3136 * Title::getAllRestrictions(), or an empty array if $getPages is
3137 * false.
3138 */
3139 public function getCascadeProtectionSources( $getPages = true ) {
3140 $pagerestrictions = [];
3141
3142 if ( $this->mCascadeSources !== null && $getPages ) {
3143 return [ $this->mCascadeSources, $this->mCascadingRestrictions ];
3144 } elseif ( $this->mHasCascadingRestrictions !== null && !$getPages ) {
3145 return [ $this->mHasCascadingRestrictions, $pagerestrictions ];
3146 }
3147
3148 $dbr = wfGetDB( DB_REPLICA );
3149
3150 if ( $this->mNamespace == NS_FILE ) {
3151 $tables = [ 'imagelinks', 'page_restrictions' ];
3152 $where_clauses = [
3153 'il_to' => $this->mDbkeyform,
3154 'il_from=pr_page',
3155 'pr_cascade' => 1
3156 ];
3157 } else {
3158 $tables = [ 'templatelinks', 'page_restrictions' ];
3159 $where_clauses = [
3160 'tl_namespace' => $this->mNamespace,
3161 'tl_title' => $this->mDbkeyform,
3162 'tl_from=pr_page',
3163 'pr_cascade' => 1
3164 ];
3165 }
3166
3167 if ( $getPages ) {
3168 $cols = [ 'pr_page', 'page_namespace', 'page_title',
3169 'pr_expiry', 'pr_type', 'pr_level' ];
3170 $where_clauses[] = 'page_id=pr_page';
3171 $tables[] = 'page';
3172 } else {
3173 $cols = [ 'pr_expiry' ];
3174 }
3175
3176 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
3177
3178 $sources = $getPages ? [] : false;
3179 $now = wfTimestampNow();
3180
3181 foreach ( $res as $row ) {
3182 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
3183 if ( $expiry > $now ) {
3184 if ( $getPages ) {
3185 $page_id = $row->pr_page;
3186 $page_ns = $row->page_namespace;
3187 $page_title = $row->page_title;
3188 $sources[$page_id] = self::makeTitle( $page_ns, $page_title );
3189 # Add groups needed for each restriction type if its not already there
3190 # Make sure this restriction type still exists
3191
3192 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
3193 $pagerestrictions[$row->pr_type] = [];
3194 }
3195
3196 if (
3197 isset( $pagerestrictions[$row->pr_type] )
3198 && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
3199 ) {
3200 $pagerestrictions[$row->pr_type][] = $row->pr_level;
3201 }
3202 } else {
3203 $sources = true;
3204 }
3205 }
3206 }
3207
3208 if ( $getPages ) {
3209 $this->mCascadeSources = $sources;
3210 $this->mCascadingRestrictions = $pagerestrictions;
3211 } else {
3212 $this->mHasCascadingRestrictions = $sources;
3213 }
3214
3215 return [ $sources, $pagerestrictions ];
3216 }
3217
3218 /**
3219 * Accessor for mRestrictionsLoaded
3220 *
3221 * @return bool Whether or not the page's restrictions have already been
3222 * loaded from the database
3223 * @since 1.23
3224 */
3225 public function areRestrictionsLoaded() {
3226 return $this->mRestrictionsLoaded;
3227 }
3228
3229 /**
3230 * Accessor/initialisation for mRestrictions
3231 *
3232 * @param string $action Action that permission needs to be checked for
3233 * @return array Restriction levels needed to take the action. All levels are
3234 * required. Note that restriction levels are normally user rights, but 'sysop'
3235 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
3236 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
3237 */
3238 public function getRestrictions( $action ) {
3239 if ( !$this->mRestrictionsLoaded ) {
3240 $this->loadRestrictions();
3241 }
3242 return $this->mRestrictions[$action] ?? [];
3243 }
3244
3245 /**
3246 * Accessor/initialisation for mRestrictions
3247 *
3248 * @return array Keys are actions, values are arrays as returned by
3249 * Title::getRestrictions()
3250 * @since 1.23
3251 */
3252 public function getAllRestrictions() {
3253 if ( !$this->mRestrictionsLoaded ) {
3254 $this->loadRestrictions();
3255 }
3256 return $this->mRestrictions;
3257 }
3258
3259 /**
3260 * Get the expiry time for the restriction against a given action
3261 *
3262 * @param string $action
3263 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
3264 * or not protected at all, or false if the action is not recognised.
3265 */
3266 public function getRestrictionExpiry( $action ) {
3267 if ( !$this->mRestrictionsLoaded ) {
3268 $this->loadRestrictions();
3269 }
3270 return $this->mRestrictionsExpiry[$action] ?? false;
3271 }
3272
3273 /**
3274 * Returns cascading restrictions for the current article
3275 *
3276 * @return bool
3277 */
3278 function areRestrictionsCascading() {
3279 if ( !$this->mRestrictionsLoaded ) {
3280 $this->loadRestrictions();
3281 }
3282
3283 return $this->mCascadeRestriction;
3284 }
3285
3286 /**
3287 * Compiles list of active page restrictions from both page table (pre 1.10)
3288 * and page_restrictions table for this existing page.
3289 * Public for usage by LiquidThreads.
3290 *
3291 * @param array $rows Array of db result objects
3292 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
3293 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3294 * Edit and move sections are separated by a colon
3295 * Example: "edit=autoconfirmed,sysop:move=sysop"
3296 */
3297 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
3298 // This function will only read rows from a table that we migrated away
3299 // from before adding READ_LATEST support to loadRestrictions, so we
3300 // don't need to support reading from DB_MASTER here.
3301 $dbr = wfGetDB( DB_REPLICA );
3302
3303 $restrictionTypes = $this->getRestrictionTypes();
3304
3305 foreach ( $restrictionTypes as $type ) {
3306 $this->mRestrictions[$type] = [];
3307 $this->mRestrictionsExpiry[$type] = 'infinity';
3308 }
3309
3310 $this->mCascadeRestriction = false;
3311
3312 # Backwards-compatibility: also load the restrictions from the page record (old format).
3313 if ( $oldFashionedRestrictions !== null ) {
3314 $this->mOldRestrictions = $oldFashionedRestrictions;
3315 }
3316
3317 if ( $this->mOldRestrictions === false ) {
3318 $this->mOldRestrictions = $dbr->selectField( 'page', 'page_restrictions',
3319 [ 'page_id' => $this->getArticleID() ], __METHOD__ );
3320 }
3321
3322 if ( $this->mOldRestrictions != '' ) {
3323 foreach ( explode( ':', trim( $this->mOldRestrictions ) ) as $restrict ) {
3324 $temp = explode( '=', trim( $restrict ) );
3325 if ( count( $temp ) == 1 ) {
3326 // old old format should be treated as edit/move restriction
3327 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
3328 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
3329 } else {
3330 $restriction = trim( $temp[1] );
3331 if ( $restriction != '' ) { // some old entries are empty
3332 $this->mRestrictions[$temp[0]] = explode( ',', $restriction );
3333 }
3334 }
3335 }
3336 }
3337
3338 if ( count( $rows ) ) {
3339 # Current system - load second to make them override.
3340 $now = wfTimestampNow();
3341
3342 # Cycle through all the restrictions.
3343 foreach ( $rows as $row ) {
3344 // Don't take care of restrictions types that aren't allowed
3345 if ( !in_array( $row->pr_type, $restrictionTypes ) ) {
3346 continue;
3347 }
3348
3349 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
3350
3351 // Only apply the restrictions if they haven't expired!
3352 if ( !$expiry || $expiry > $now ) {
3353 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
3354 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
3355
3356 $this->mCascadeRestriction |= $row->pr_cascade;
3357 }
3358 }
3359 }
3360
3361 $this->mRestrictionsLoaded = true;
3362 }
3363
3364 /**
3365 * Load restrictions from the page_restrictions table
3366 *
3367 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
3368 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3369 * Edit and move sections are separated by a colon
3370 * Example: "edit=autoconfirmed,sysop:move=sysop"
3371 * @param int $flags A bit field. If self::READ_LATEST is set, skip replicas and read
3372 * from the master DB.
3373 */
3374 public function loadRestrictions( $oldFashionedRestrictions = null, $flags = 0 ) {
3375 $readLatest = DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST );
3376 if ( $this->mRestrictionsLoaded && !$readLatest ) {
3377 return;
3378 }
3379
3380 // TODO: should probably pass $flags into getArticleID, but it seems hacky
3381 // to mix READ_LATEST and GAID_FOR_UPDATE, even if they have the same value.
3382 // Maybe deprecate GAID_FOR_UPDATE now that we implement IDBAccessObject?
3383 $id = $this->getArticleID();
3384 if ( $id ) {
3385 $fname = __METHOD__;
3386 $loadRestrictionsFromDb = function ( Database $dbr ) use ( $fname, $id ) {
3387 return iterator_to_array(
3388 $dbr->select(
3389 'page_restrictions',
3390 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
3391 [ 'pr_page' => $id ],
3392 $fname
3393 )
3394 );
3395 };
3396
3397 if ( $readLatest ) {
3398 $dbr = wfGetDB( DB_MASTER );
3399 $rows = $loadRestrictionsFromDb( $dbr );
3400 } else {
3401 $cache = ObjectCache::getMainWANInstance();
3402 $rows = $cache->getWithSetCallback(
3403 // Page protections always leave a new null revision
3404 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
3405 $cache::TTL_DAY,
3406 function ( $curValue, &$ttl, array &$setOpts ) use ( $loadRestrictionsFromDb ) {
3407 $dbr = wfGetDB( DB_REPLICA );
3408
3409 $setOpts += Database::getCacheSetOptions( $dbr );
3410
3411 return $loadRestrictionsFromDb( $dbr );
3412 }
3413 );
3414 }
3415
3416 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
3417 } else {
3418 $title_protection = $this->getTitleProtectionInternal();
3419
3420 if ( $title_protection ) {
3421 $now = wfTimestampNow();
3422 $expiry = wfGetDB( DB_REPLICA )->decodeExpiry( $title_protection['expiry'] );
3423
3424 if ( !$expiry || $expiry > $now ) {
3425 // Apply the restrictions
3426 $this->mRestrictionsExpiry['create'] = $expiry;
3427 $this->mRestrictions['create'] =
3428 explode( ',', trim( $title_protection['permission'] ) );
3429 } else { // Get rid of the old restrictions
3430 $this->mTitleProtection = false;
3431 }
3432 } else {
3433 $this->mRestrictionsExpiry['create'] = 'infinity';
3434 }
3435 $this->mRestrictionsLoaded = true;
3436 }
3437 }
3438
3439 /**
3440 * Flush the protection cache in this object and force reload from the database.
3441 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3442 */
3443 public function flushRestrictions() {
3444 $this->mRestrictionsLoaded = false;
3445 $this->mTitleProtection = null;
3446 }
3447
3448 /**
3449 * Purge expired restrictions from the page_restrictions table
3450 *
3451 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3452 */
3453 static function purgeExpiredRestrictions() {
3454 if ( wfReadOnly() ) {
3455 return;
3456 }
3457
3458 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
3459 wfGetDB( DB_MASTER ),
3460 __METHOD__,
3461 function ( IDatabase $dbw, $fname ) {
3462 $config = MediaWikiServices::getInstance()->getMainConfig();
3463 $ids = $dbw->selectFieldValues(
3464 'page_restrictions',
3465 'pr_id',
3466 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3467 $fname,
3468 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3469 );
3470 if ( $ids ) {
3471 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3472 }
3473 }
3474 ) );
3475
3476 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
3477 wfGetDB( DB_MASTER ),
3478 __METHOD__,
3479 function ( IDatabase $dbw, $fname ) {
3480 $dbw->delete(
3481 'protected_titles',
3482 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3483 $fname
3484 );
3485 }
3486 ) );
3487 }
3488
3489 /**
3490 * Does this have subpages? (Warning, usually requires an extra DB query.)
3491 *
3492 * @return bool
3493 */
3494 public function hasSubpages() {
3495 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
3496 # Duh
3497 return false;
3498 }
3499
3500 # We dynamically add a member variable for the purpose of this method
3501 # alone to cache the result. There's no point in having it hanging
3502 # around uninitialized in every Title object; therefore we only add it
3503 # if needed and don't declare it statically.
3504 if ( $this->mHasSubpages === null ) {
3505 $this->mHasSubpages = false;
3506 $subpages = $this->getSubpages( 1 );
3507 if ( $subpages instanceof TitleArray ) {
3508 $this->mHasSubpages = (bool)$subpages->count();
3509 }
3510 }
3511
3512 return $this->mHasSubpages;
3513 }
3514
3515 /**
3516 * Get all subpages of this page.
3517 *
3518 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3519 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3520 * doesn't allow subpages
3521 */
3522 public function getSubpages( $limit = -1 ) {
3523 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
3524 return [];
3525 }
3526
3527 $dbr = wfGetDB( DB_REPLICA );
3528 $conds['page_namespace'] = $this->mNamespace;
3529 $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform . '/', $dbr->anyString() );
3530 $options = [];
3531 if ( $limit > -1 ) {
3532 $options['LIMIT'] = $limit;
3533 }
3534 return TitleArray::newFromResult(
3535 $dbr->select( 'page',
3536 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3537 $conds,
3538 __METHOD__,
3539 $options
3540 )
3541 );
3542 }
3543
3544 /**
3545 * Is there a version of this page in the deletion archive?
3546 *
3547 * @return int The number of archived revisions
3548 */
3549 public function isDeleted() {
3550 if ( $this->mNamespace < 0 ) {
3551 $n = 0;
3552 } else {
3553 $dbr = wfGetDB( DB_REPLICA );
3554
3555 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3556 [ 'ar_namespace' => $this->mNamespace, 'ar_title' => $this->mDbkeyform ],
3557 __METHOD__
3558 );
3559 if ( $this->mNamespace == NS_FILE ) {
3560 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
3561 [ 'fa_name' => $this->mDbkeyform ],
3562 __METHOD__
3563 );
3564 }
3565 }
3566 return (int)$n;
3567 }
3568
3569 /**
3570 * Is there a version of this page in the deletion archive?
3571 *
3572 * @return bool
3573 */
3574 public function isDeletedQuick() {
3575 if ( $this->mNamespace < 0 ) {
3576 return false;
3577 }
3578 $dbr = wfGetDB( DB_REPLICA );
3579 $deleted = (bool)$dbr->selectField( 'archive', '1',
3580 [ 'ar_namespace' => $this->mNamespace, 'ar_title' => $this->mDbkeyform ],
3581 __METHOD__
3582 );
3583 if ( !$deleted && $this->mNamespace == NS_FILE ) {
3584 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3585 [ 'fa_name' => $this->mDbkeyform ],
3586 __METHOD__
3587 );
3588 }
3589 return $deleted;
3590 }
3591
3592 /**
3593 * Get the article ID for this Title from the link cache,
3594 * adding it if necessary
3595 *
3596 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3597 * for update
3598 * @return int The ID
3599 */
3600 public function getArticleID( $flags = 0 ) {
3601 if ( $this->mNamespace < 0 ) {
3602 $this->mArticleID = 0;
3603 return $this->mArticleID;
3604 }
3605 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3606 if ( $flags & self::GAID_FOR_UPDATE ) {
3607 $oldUpdate = $linkCache->forUpdate( true );
3608 $linkCache->clearLink( $this );
3609 $this->mArticleID = $linkCache->addLinkObj( $this );
3610 $linkCache->forUpdate( $oldUpdate );
3611 } else {
3612 if ( $this->mArticleID == -1 ) {
3613 $this->mArticleID = $linkCache->addLinkObj( $this );
3614 }
3615 }
3616 return $this->mArticleID;
3617 }
3618
3619 /**
3620 * Is this an article that is a redirect page?
3621 * Uses link cache, adding it if necessary
3622 *
3623 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3624 * @return bool
3625 */
3626 public function isRedirect( $flags = 0 ) {
3627 if ( !is_null( $this->mRedirect ) ) {
3628 return $this->mRedirect;
3629 }
3630 if ( !$this->getArticleID( $flags ) ) {
3631 $this->mRedirect = false;
3632 return $this->mRedirect;
3633 }
3634
3635 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3636 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3637 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3638 if ( $cached === null ) {
3639 # Trust LinkCache's state over our own
3640 # LinkCache is telling us that the page doesn't exist, despite there being cached
3641 # data relating to an existing page in $this->mArticleID. Updaters should clear
3642 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3643 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3644 # LinkCache to refresh its data from the master.
3645 $this->mRedirect = false;
3646 return $this->mRedirect;
3647 }
3648
3649 $this->mRedirect = (bool)$cached;
3650
3651 return $this->mRedirect;
3652 }
3653
3654 /**
3655 * What is the length of this page?
3656 * Uses link cache, adding it if necessary
3657 *
3658 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3659 * @return int
3660 */
3661 public function getLength( $flags = 0 ) {
3662 if ( $this->mLength != -1 ) {
3663 return $this->mLength;
3664 }
3665 if ( !$this->getArticleID( $flags ) ) {
3666 $this->mLength = 0;
3667 return $this->mLength;
3668 }
3669 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3670 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3671 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3672 if ( $cached === null ) {
3673 # Trust LinkCache's state over our own, as for isRedirect()
3674 $this->mLength = 0;
3675 return $this->mLength;
3676 }
3677
3678 $this->mLength = intval( $cached );
3679
3680 return $this->mLength;
3681 }
3682
3683 /**
3684 * What is the page_latest field for this page?
3685 *
3686 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3687 * @return int Int or 0 if the page doesn't exist
3688 */
3689 public function getLatestRevID( $flags = 0 ) {
3690 if ( !( $flags & self::GAID_FOR_UPDATE ) && $this->mLatestID !== false ) {
3691 return intval( $this->mLatestID );
3692 }
3693 if ( !$this->getArticleID( $flags ) ) {
3694 $this->mLatestID = 0;
3695 return $this->mLatestID;
3696 }
3697 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3698 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3699 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3700 if ( $cached === null ) {
3701 # Trust LinkCache's state over our own, as for isRedirect()
3702 $this->mLatestID = 0;
3703 return $this->mLatestID;
3704 }
3705
3706 $this->mLatestID = intval( $cached );
3707
3708 return $this->mLatestID;
3709 }
3710
3711 /**
3712 * This clears some fields in this object, and clears any associated
3713 * keys in the "bad links" section of the link cache.
3714 *
3715 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3716 * loading of the new page_id. It's also called from
3717 * WikiPage::doDeleteArticleReal()
3718 *
3719 * @param int $newid The new Article ID
3720 */
3721 public function resetArticleID( $newid ) {
3722 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3723 $linkCache->clearLink( $this );
3724
3725 if ( $newid === false ) {
3726 $this->mArticleID = -1;
3727 } else {
3728 $this->mArticleID = intval( $newid );
3729 }
3730 $this->mRestrictionsLoaded = false;
3731 $this->mRestrictions = [];
3732 $this->mOldRestrictions = false;
3733 $this->mRedirect = null;
3734 $this->mLength = -1;
3735 $this->mLatestID = false;
3736 $this->mContentModel = false;
3737 $this->mEstimateRevisions = null;
3738 $this->mPageLanguage = false;
3739 $this->mDbPageLanguage = false;
3740 $this->mIsBigDeletion = null;
3741 }
3742
3743 public static function clearCaches() {
3744 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3745 $linkCache->clear();
3746
3747 $titleCache = self::getTitleCache();
3748 $titleCache->clear();
3749 }
3750
3751 /**
3752 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3753 *
3754 * @param string $text Containing title to capitalize
3755 * @param int $ns Namespace index, defaults to NS_MAIN
3756 * @return string Containing capitalized title
3757 */
3758 public static function capitalize( $text, $ns = NS_MAIN ) {
3759 if ( MWNamespace::isCapitalized( $ns ) ) {
3760 return MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $text );
3761 } else {
3762 return $text;
3763 }
3764 }
3765
3766 /**
3767 * Secure and split - main initialisation function for this object
3768 *
3769 * Assumes that mDbkeyform has been set, and is urldecoded
3770 * and uses underscores, but not otherwise munged. This function
3771 * removes illegal characters, splits off the interwiki and
3772 * namespace prefixes, sets the other forms, and canonicalizes
3773 * everything.
3774 *
3775 * @throws MalformedTitleException On invalid titles
3776 * @return bool True on success
3777 */
3778 private function secureAndSplit() {
3779 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3780 // the parsing code with Title, while avoiding massive refactoring.
3781 // @todo: get rid of secureAndSplit, refactor parsing code.
3782 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3783 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3784 $titleCodec = MediaWikiServices::getInstance()->getTitleParser();
3785 // MalformedTitleException can be thrown here
3786 $parts = $titleCodec->splitTitleString( $this->mDbkeyform, $this->mDefaultNamespace );
3787
3788 # Fill fields
3789 $this->setFragment( '#' . $parts['fragment'] );
3790 $this->mInterwiki = $parts['interwiki'];
3791 $this->mLocalInterwiki = $parts['local_interwiki'];
3792 $this->mNamespace = $parts['namespace'];
3793 $this->mUserCaseDBKey = $parts['user_case_dbkey'];
3794
3795 $this->mDbkeyform = $parts['dbkey'];
3796 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
3797 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
3798
3799 # We already know that some pages won't be in the database!
3800 if ( $this->isExternal() || $this->isSpecialPage() ) {
3801 $this->mArticleID = 0;
3802 }
3803
3804 return true;
3805 }
3806
3807 /**
3808 * Get an array of Title objects linking to this Title
3809 * Also stores the IDs in the link cache.
3810 *
3811 * WARNING: do not use this function on arbitrary user-supplied titles!
3812 * On heavily-used templates it will max out the memory.
3813 *
3814 * @param array $options May be FOR UPDATE
3815 * @param string $table Table name
3816 * @param string $prefix Fields prefix
3817 * @return Title[] Array of Title objects linking here
3818 */
3819 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3820 if ( count( $options ) > 0 ) {
3821 $db = wfGetDB( DB_MASTER );
3822 } else {
3823 $db = wfGetDB( DB_REPLICA );
3824 }
3825
3826 $res = $db->select(
3827 [ 'page', $table ],
3828 self::getSelectFields(),
3829 [
3830 "{$prefix}_from=page_id",
3831 "{$prefix}_namespace" => $this->mNamespace,
3832 "{$prefix}_title" => $this->mDbkeyform ],
3833 __METHOD__,
3834 $options
3835 );
3836
3837 $retVal = [];
3838 if ( $res->numRows() ) {
3839 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3840 foreach ( $res as $row ) {
3841 $titleObj = self::makeTitle( $row->page_namespace, $row->page_title );
3842 if ( $titleObj ) {
3843 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3844 $retVal[] = $titleObj;
3845 }
3846 }
3847 }
3848 return $retVal;
3849 }
3850
3851 /**
3852 * Get an array of Title objects using this Title as a template
3853 * Also stores the IDs in the link cache.
3854 *
3855 * WARNING: do not use this function on arbitrary user-supplied titles!
3856 * On heavily-used templates it will max out the memory.
3857 *
3858 * @param array $options Query option to Database::select()
3859 * @return Title[] Array of Title the Title objects linking here
3860 */
3861 public function getTemplateLinksTo( $options = [] ) {
3862 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3863 }
3864
3865 /**
3866 * Get an array of Title objects linked from this Title
3867 * Also stores the IDs in the link cache.
3868 *
3869 * WARNING: do not use this function on arbitrary user-supplied titles!
3870 * On heavily-used templates it will max out the memory.
3871 *
3872 * @param array $options Query option to Database::select()
3873 * @param string $table Table name
3874 * @param string $prefix Fields prefix
3875 * @return array Array of Title objects linking here
3876 */
3877 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3878 $id = $this->getArticleID();
3879
3880 # If the page doesn't exist; there can't be any link from this page
3881 if ( !$id ) {
3882 return [];
3883 }
3884
3885 $db = wfGetDB( DB_REPLICA );
3886
3887 $blNamespace = "{$prefix}_namespace";
3888 $blTitle = "{$prefix}_title";
3889
3890 $pageQuery = WikiPage::getQueryInfo();
3891 $res = $db->select(
3892 [ $table, 'nestpage' => $pageQuery['tables'] ],
3893 array_merge(
3894 [ $blNamespace, $blTitle ],
3895 $pageQuery['fields']
3896 ),
3897 [ "{$prefix}_from" => $id ],
3898 __METHOD__,
3899 $options,
3900 [ 'nestpage' => [
3901 'LEFT JOIN',
3902 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3903 ] ] + $pageQuery['joins']
3904 );
3905
3906 $retVal = [];
3907 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
3908 foreach ( $res as $row ) {
3909 if ( $row->page_id ) {
3910 $titleObj = self::newFromRow( $row );
3911 } else {
3912 $titleObj = self::makeTitle( $row->$blNamespace, $row->$blTitle );
3913 $linkCache->addBadLinkObj( $titleObj );
3914 }
3915 $retVal[] = $titleObj;
3916 }
3917
3918 return $retVal;
3919 }
3920
3921 /**
3922 * Get an array of Title objects used on this Title as a template
3923 * Also stores the IDs in the link cache.
3924 *
3925 * WARNING: do not use this function on arbitrary user-supplied titles!
3926 * On heavily-used templates it will max out the memory.
3927 *
3928 * @param array $options May be FOR UPDATE
3929 * @return Title[] Array of Title the Title objects used here
3930 */
3931 public function getTemplateLinksFrom( $options = [] ) {
3932 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3933 }
3934
3935 /**
3936 * Get an array of Title objects referring to non-existent articles linked
3937 * from this page.
3938 *
3939 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3940 * should use redirect table in this case).
3941 * @return Title[] Array of Title the Title objects
3942 */
3943 public function getBrokenLinksFrom() {
3944 if ( $this->getArticleID() == 0 ) {
3945 # All links from article ID 0 are false positives
3946 return [];
3947 }
3948
3949 $dbr = wfGetDB( DB_REPLICA );
3950 $res = $dbr->select(
3951 [ 'page', 'pagelinks' ],
3952 [ 'pl_namespace', 'pl_title' ],
3953 [
3954 'pl_from' => $this->getArticleID(),
3955 'page_namespace IS NULL'
3956 ],
3957 __METHOD__, [],
3958 [
3959 'page' => [
3960 'LEFT JOIN',
3961 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3962 ]
3963 ]
3964 );
3965
3966 $retVal = [];
3967 foreach ( $res as $row ) {
3968 $retVal[] = self::makeTitle( $row->pl_namespace, $row->pl_title );
3969 }
3970 return $retVal;
3971 }
3972
3973 /**
3974 * Get a list of URLs to purge from the CDN cache when this
3975 * page changes
3976 *
3977 * @return string[] Array of String the URLs
3978 */
3979 public function getCdnUrls() {
3980 $urls = [
3981 $this->getInternalURL(),
3982 $this->getInternalURL( 'action=history' )
3983 ];
3984
3985 $pageLang = $this->getPageLanguage();
3986 if ( $pageLang->hasVariants() ) {
3987 $variants = $pageLang->getVariants();
3988 foreach ( $variants as $vCode ) {
3989 $urls[] = $this->getInternalURL( $vCode );
3990 }
3991 }
3992
3993 // If we are looking at a css/js user subpage, purge the action=raw.
3994 if ( $this->isUserJsConfigPage() ) {
3995 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3996 } elseif ( $this->isUserJsonConfigPage() ) {
3997 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3998 } elseif ( $this->isUserCssConfigPage() ) {
3999 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
4000 }
4001
4002 Hooks::run( 'TitleSquidURLs', [ $this, &$urls ] );
4003 return $urls;
4004 }
4005
4006 /**
4007 * Purge all applicable CDN URLs
4008 */
4009 public function purgeSquid() {
4010 DeferredUpdates::addUpdate(
4011 new CdnCacheUpdate( $this->getCdnUrls() ),
4012 DeferredUpdates::PRESEND
4013 );
4014 }
4015
4016 /**
4017 * Check whether a given move operation would be valid.
4018 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
4019 *
4020 * @deprecated since 1.25, use MovePage's methods instead
4021 * @param Title &$nt The new title
4022 * @param bool $auth Whether to check user permissions (uses $wgUser)
4023 * @param string $reason Is the log summary of the move, used for spam checking
4024 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
4025 */
4026 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
4027 global $wgUser;
4028
4029 if ( !( $nt instanceof Title ) ) {
4030 // Normally we'd add this to $errors, but we'll get
4031 // lots of syntax errors if $nt is not an object
4032 return [ [ 'badtitletext' ] ];
4033 }
4034
4035 $mp = new MovePage( $this, $nt );
4036 $errors = $mp->isValidMove()->getErrorsArray();
4037 if ( $auth ) {
4038 $errors = wfMergeErrorArrays(
4039 $errors,
4040 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
4041 );
4042 }
4043
4044 return $errors ?: true;
4045 }
4046
4047 /**
4048 * Check if the requested move target is a valid file move target
4049 * @todo move this to MovePage
4050 * @param Title $nt Target title
4051 * @return array List of errors
4052 */
4053 protected function validateFileMoveOperation( $nt ) {
4054 global $wgUser;
4055
4056 $errors = [];
4057
4058 $destFile = wfLocalFile( $nt );
4059 $destFile->load( File::READ_LATEST );
4060 if ( !$wgUser->isAllowed( 'reupload-shared' )
4061 && !$destFile->exists() && wfFindFile( $nt )
4062 ) {
4063 $errors[] = [ 'file-exists-sharedrepo' ];
4064 }
4065
4066 return $errors;
4067 }
4068
4069 /**
4070 * Move a title to a new location
4071 *
4072 * @deprecated since 1.25, use the MovePage class instead
4073 * @param Title &$nt The new title
4074 * @param bool $auth Indicates whether $wgUser's permissions
4075 * should be checked
4076 * @param string $reason The reason for the move
4077 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
4078 * Ignored if the user doesn't have the suppressredirect right.
4079 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4080 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
4081 */
4082 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
4083 array $changeTags = []
4084 ) {
4085 global $wgUser;
4086 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
4087 if ( is_array( $err ) ) {
4088 // Auto-block user's IP if the account was "hard" blocked
4089 $wgUser->spreadAnyEditBlock();
4090 return $err;
4091 }
4092 // Check suppressredirect permission
4093 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
4094 $createRedirect = true;
4095 }
4096
4097 $mp = new MovePage( $this, $nt );
4098 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
4099 if ( $status->isOK() ) {
4100 return true;
4101 } else {
4102 return $status->getErrorsArray();
4103 }
4104 }
4105
4106 /**
4107 * Move this page's subpages to be subpages of $nt
4108 *
4109 * @param Title $nt Move target
4110 * @param bool $auth Whether $wgUser's permissions should be checked
4111 * @param string $reason The reason for the move
4112 * @param bool $createRedirect Whether to create redirects from the old subpages to
4113 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
4114 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4115 * @return array Array with old page titles as keys, and strings (new page titles) or
4116 * getUserPermissionsErrors()-like arrays (errors) as values, or a
4117 * getUserPermissionsErrors()-like error array with numeric indices if
4118 * no pages were moved
4119 */
4120 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
4121 array $changeTags = []
4122 ) {
4123 global $wgMaximumMovedPages;
4124 // Check permissions
4125 if ( !$this->userCan( 'move-subpages' ) ) {
4126 return [
4127 [ 'cant-move-subpages' ],
4128 ];
4129 }
4130 // Do the source and target namespaces support subpages?
4131 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
4132 return [
4133 [ 'namespace-nosubpages', MWNamespace::getCanonicalName( $this->mNamespace ) ],
4134 ];
4135 }
4136 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
4137 return [
4138 [ 'namespace-nosubpages', MWNamespace::getCanonicalName( $nt->getNamespace() ) ],
4139 ];
4140 }
4141
4142 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
4143 $retval = [];
4144 $count = 0;
4145 foreach ( $subpages as $oldSubpage ) {
4146 $count++;
4147 if ( $count > $wgMaximumMovedPages ) {
4148 $retval[$oldSubpage->getPrefixedText()] = [
4149 [ 'movepage-max-pages', $wgMaximumMovedPages ],
4150 ];
4151 break;
4152 }
4153
4154 // We don't know whether this function was called before
4155 // or after moving the root page, so check both
4156 // $this and $nt
4157 if ( $oldSubpage->getArticleID() == $this->getArticleID()
4158 || $oldSubpage->getArticleID() == $nt->getArticleID()
4159 ) {
4160 // When moving a page to a subpage of itself,
4161 // don't move it twice
4162 continue;
4163 }
4164 $newPageName = preg_replace(
4165 '#^' . preg_quote( $this->mDbkeyform, '#' ) . '#',
4166 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # T23234
4167 $oldSubpage->getDBkey() );
4168 if ( $oldSubpage->isTalkPage() ) {
4169 $newNs = $nt->getTalkPage()->getNamespace();
4170 } else {
4171 $newNs = $nt->getSubjectPage()->getNamespace();
4172 }
4173 # T16385: we need makeTitleSafe because the new page names may
4174 # be longer than 255 characters.
4175 $newSubpage = self::makeTitleSafe( $newNs, $newPageName );
4176
4177 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
4178 if ( $success === true ) {
4179 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
4180 } else {
4181 $retval[$oldSubpage->getPrefixedText()] = $success;
4182 }
4183 }
4184 return $retval;
4185 }
4186
4187 /**
4188 * Checks if this page is just a one-rev redirect.
4189 * Adds lock, so don't use just for light purposes.
4190 *
4191 * @return bool
4192 */
4193 public function isSingleRevRedirect() {
4194 global $wgContentHandlerUseDB;
4195
4196 $dbw = wfGetDB( DB_MASTER );
4197
4198 # Is it a redirect?
4199 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
4200 if ( $wgContentHandlerUseDB ) {
4201 $fields[] = 'page_content_model';
4202 }
4203
4204 $row = $dbw->selectRow( 'page',
4205 $fields,
4206 $this->pageCond(),
4207 __METHOD__,
4208 [ 'FOR UPDATE' ]
4209 );
4210 # Cache some fields we may want
4211 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
4212 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
4213 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
4214 $this->mContentModel = $row && isset( $row->page_content_model )
4215 ? strval( $row->page_content_model )
4216 : false;
4217
4218 if ( !$this->mRedirect ) {
4219 return false;
4220 }
4221 # Does the article have a history?
4222 $row = $dbw->selectField( [ 'page', 'revision' ],
4223 'rev_id',
4224 [ 'page_namespace' => $this->mNamespace,
4225 'page_title' => $this->mDbkeyform,
4226 'page_id=rev_page',
4227 'page_latest != rev_id'
4228 ],
4229 __METHOD__,
4230 [ 'FOR UPDATE' ]
4231 );
4232 # Return true if there was no history
4233 return ( $row === false );
4234 }
4235
4236 /**
4237 * Checks if $this can be moved to a given Title
4238 * - Selects for update, so don't call it unless you mean business
4239 *
4240 * @deprecated since 1.25, use MovePage's methods instead
4241 * @param Title $nt The new title to check
4242 * @return bool
4243 */
4244 public function isValidMoveTarget( $nt ) {
4245 # Is it an existing file?
4246 if ( $nt->getNamespace() == NS_FILE ) {
4247 $file = wfLocalFile( $nt );
4248 $file->load( File::READ_LATEST );
4249 if ( $file->exists() ) {
4250 wfDebug( __METHOD__ . ": file exists\n" );
4251 return false;
4252 }
4253 }
4254 # Is it a redirect with no history?
4255 if ( !$nt->isSingleRevRedirect() ) {
4256 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
4257 return false;
4258 }
4259 # Get the article text
4260 $rev = Revision::newFromTitle( $nt, false, Revision::READ_LATEST );
4261 if ( !is_object( $rev ) ) {
4262 return false;
4263 }
4264 $content = $rev->getContent();
4265 # Does the redirect point to the source?
4266 # Or is it a broken self-redirect, usually caused by namespace collisions?
4267 $redirTitle = $content ? $content->getRedirectTarget() : null;
4268
4269 if ( $redirTitle ) {
4270 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4271 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4272 wfDebug( __METHOD__ . ": redirect points to other page\n" );
4273 return false;
4274 } else {
4275 return true;
4276 }
4277 } else {
4278 # Fail safe (not a redirect after all. strange.)
4279 wfDebug( __METHOD__ . ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4280 " is a redirect, but it doesn't contain a valid redirect.\n" );
4281 return false;
4282 }
4283 }
4284
4285 /**
4286 * Get categories to which this Title belongs and return an array of
4287 * categories' names.
4288 *
4289 * @return array Array of parents in the form:
4290 * $parent => $currentarticle
4291 */
4292 public function getParentCategories() {
4293 $data = [];
4294
4295 $titleKey = $this->getArticleID();
4296
4297 if ( $titleKey === 0 ) {
4298 return $data;
4299 }
4300
4301 $dbr = wfGetDB( DB_REPLICA );
4302
4303 $res = $dbr->select(
4304 'categorylinks',
4305 'cl_to',
4306 [ 'cl_from' => $titleKey ],
4307 __METHOD__
4308 );
4309
4310 if ( $res->numRows() > 0 ) {
4311 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
4312 foreach ( $res as $row ) {
4313 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4314 $data[$contLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] =
4315 $this->getFullText();
4316 }
4317 }
4318 return $data;
4319 }
4320
4321 /**
4322 * Get a tree of parent categories
4323 *
4324 * @param array $children Array with the children in the keys, to check for circular refs
4325 * @return array Tree of parent categories
4326 */
4327 public function getParentCategoryTree( $children = [] ) {
4328 $stack = [];
4329 $parents = $this->getParentCategories();
4330
4331 if ( $parents ) {
4332 foreach ( $parents as $parent => $current ) {
4333 if ( array_key_exists( $parent, $children ) ) {
4334 # Circular reference
4335 $stack[$parent] = [];
4336 } else {
4337 $nt = self::newFromText( $parent );
4338 if ( $nt ) {
4339 $stack[$parent] = $nt->getParentCategoryTree( $children + [ $parent => 1 ] );
4340 }
4341 }
4342 }
4343 }
4344
4345 return $stack;
4346 }
4347
4348 /**
4349 * Get an associative array for selecting this title from
4350 * the "page" table
4351 *
4352 * @return array Array suitable for the $where parameter of DB::select()
4353 */
4354 public function pageCond() {
4355 if ( $this->mArticleID > 0 ) {
4356 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4357 return [ 'page_id' => $this->mArticleID ];
4358 } else {
4359 return [ 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform ];
4360 }
4361 }
4362
4363 /**
4364 * Get next/previous revision ID relative to another revision ID
4365 * @param int $revId Revision ID. Get the revision that was before this one.
4366 * @param int $flags Title::GAID_FOR_UPDATE
4367 * @param string $dir 'next' or 'prev'
4368 * @return int|bool New revision ID, or false if none exists
4369 */
4370 private function getRelativeRevisionID( $revId, $flags, $dir ) {
4371 $revId = (int)$revId;
4372 if ( $dir === 'next' ) {
4373 $op = '>';
4374 $sort = 'ASC';
4375 } elseif ( $dir === 'prev' ) {
4376 $op = '<';
4377 $sort = 'DESC';
4378 } else {
4379 throw new InvalidArgumentException( '$dir must be "next" or "prev"' );
4380 }
4381
4382 if ( $flags & self::GAID_FOR_UPDATE ) {
4383 $db = wfGetDB( DB_MASTER );
4384 } else {
4385 $db = wfGetDB( DB_REPLICA, 'contributions' );
4386 }
4387
4388 // Intentionally not caring if the specified revision belongs to this
4389 // page. We only care about the timestamp.
4390 $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__ );
4391 if ( $ts === false ) {
4392 $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__ );
4393 if ( $ts === false ) {
4394 // Or should this throw an InvalidArgumentException or something?
4395 return false;
4396 }
4397 }
4398 $ts = $db->addQuotes( $ts );
4399
4400 $revId = $db->selectField( 'revision', 'rev_id',
4401 [
4402 'rev_page' => $this->getArticleID( $flags ),
4403 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)"
4404 ],
4405 __METHOD__,
4406 [
4407 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
4408 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
4409 ]
4410 );
4411
4412 if ( $revId === false ) {
4413 return false;
4414 } else {
4415 return intval( $revId );
4416 }
4417 }
4418
4419 /**
4420 * Get the revision ID of the previous revision
4421 *
4422 * @param int $revId Revision ID. Get the revision that was before this one.
4423 * @param int $flags Title::GAID_FOR_UPDATE
4424 * @return int|bool Old revision ID, or false if none exists
4425 */
4426 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4427 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
4428 }
4429
4430 /**
4431 * Get the revision ID of the next revision
4432 *
4433 * @param int $revId Revision ID. Get the revision that was after this one.
4434 * @param int $flags Title::GAID_FOR_UPDATE
4435 * @return int|bool Next revision ID, or false if none exists
4436 */
4437 public function getNextRevisionID( $revId, $flags = 0 ) {
4438 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
4439 }
4440
4441 /**
4442 * Get the first revision of the page
4443 *
4444 * @param int $flags Title::GAID_FOR_UPDATE
4445 * @return Revision|null If page doesn't exist
4446 */
4447 public function getFirstRevision( $flags = 0 ) {
4448 $pageId = $this->getArticleID( $flags );
4449 if ( $pageId ) {
4450 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_REPLICA );
4451 $revQuery = Revision::getQueryInfo();
4452 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
4453 [ 'rev_page' => $pageId ],
4454 __METHOD__,
4455 [
4456 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
4457 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
4458 ],
4459 $revQuery['joins']
4460 );
4461 if ( $row ) {
4462 return new Revision( $row, 0, $this );
4463 }
4464 }
4465 return null;
4466 }
4467
4468 /**
4469 * Get the oldest revision timestamp of this page
4470 *
4471 * @param int $flags Title::GAID_FOR_UPDATE
4472 * @return string|null MW timestamp
4473 */
4474 public function getEarliestRevTime( $flags = 0 ) {
4475 $rev = $this->getFirstRevision( $flags );
4476 return $rev ? $rev->getTimestamp() : null;
4477 }
4478
4479 /**
4480 * Check if this is a new page
4481 *
4482 * @return bool
4483 */
4484 public function isNewPage() {
4485 $dbr = wfGetDB( DB_REPLICA );
4486 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
4487 }
4488
4489 /**
4490 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4491 *
4492 * @return bool
4493 */
4494 public function isBigDeletion() {
4495 global $wgDeleteRevisionsLimit;
4496
4497 if ( !$wgDeleteRevisionsLimit ) {
4498 return false;
4499 }
4500
4501 if ( $this->mIsBigDeletion === null ) {
4502 $dbr = wfGetDB( DB_REPLICA );
4503
4504 $revCount = $dbr->selectRowCount(
4505 'revision',
4506 '1',
4507 [ 'rev_page' => $this->getArticleID() ],
4508 __METHOD__,
4509 [ 'LIMIT' => $wgDeleteRevisionsLimit + 1 ]
4510 );
4511
4512 $this->mIsBigDeletion = $revCount > $wgDeleteRevisionsLimit;
4513 }
4514
4515 return $this->mIsBigDeletion;
4516 }
4517
4518 /**
4519 * Get the approximate revision count of this page.
4520 *
4521 * @return int
4522 */
4523 public function estimateRevisionCount() {
4524 if ( !$this->exists() ) {
4525 return 0;
4526 }
4527
4528 if ( $this->mEstimateRevisions === null ) {
4529 $dbr = wfGetDB( DB_REPLICA );
4530 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
4531 [ 'rev_page' => $this->getArticleID() ], __METHOD__ );
4532 }
4533
4534 return $this->mEstimateRevisions;
4535 }
4536
4537 /**
4538 * Get the number of revisions between the given revision.
4539 * Used for diffs and other things that really need it.
4540 *
4541 * @param int|Revision $old Old revision or rev ID (first before range)
4542 * @param int|Revision $new New revision or rev ID (first after range)
4543 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4544 * @return int Number of revisions between these revisions.
4545 */
4546 public function countRevisionsBetween( $old, $new, $max = null ) {
4547 if ( !( $old instanceof Revision ) ) {
4548 $old = Revision::newFromTitle( $this, (int)$old );
4549 }
4550 if ( !( $new instanceof Revision ) ) {
4551 $new = Revision::newFromTitle( $this, (int)$new );
4552 }
4553 if ( !$old || !$new ) {
4554 return 0; // nothing to compare
4555 }
4556 $dbr = wfGetDB( DB_REPLICA );
4557 $conds = [
4558 'rev_page' => $this->getArticleID(),
4559 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4560 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4561 ];
4562 if ( $max !== null ) {
4563 return $dbr->selectRowCount( 'revision', '1',
4564 $conds,
4565 __METHOD__,
4566 [ 'LIMIT' => $max + 1 ] // extra to detect truncation
4567 );
4568 } else {
4569 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__ );
4570 }
4571 }
4572
4573 /**
4574 * Get the authors between the given revisions or revision IDs.
4575 * Used for diffs and other things that really need it.
4576 *
4577 * @since 1.23
4578 *
4579 * @param int|Revision $old Old revision or rev ID (first before range by default)
4580 * @param int|Revision $new New revision or rev ID (first after range by default)
4581 * @param int $limit Maximum number of authors
4582 * @param string|array $options (Optional): Single option, or an array of options:
4583 * 'include_old' Include $old in the range; $new is excluded.
4584 * 'include_new' Include $new in the range; $old is excluded.
4585 * 'include_both' Include both $old and $new in the range.
4586 * Unknown option values are ignored.
4587 * @return array|null Names of revision authors in the range; null if not both revisions exist
4588 */
4589 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4590 if ( !( $old instanceof Revision ) ) {
4591 $old = Revision::newFromTitle( $this, (int)$old );
4592 }
4593 if ( !( $new instanceof Revision ) ) {
4594 $new = Revision::newFromTitle( $this, (int)$new );
4595 }
4596 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4597 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4598 // in the sanity check below?
4599 if ( !$old || !$new ) {
4600 return null; // nothing to compare
4601 }
4602 $authors = [];
4603 $old_cmp = '>';
4604 $new_cmp = '<';
4605 $options = (array)$options;
4606 if ( in_array( 'include_old', $options ) ) {
4607 $old_cmp = '>=';
4608 }
4609 if ( in_array( 'include_new', $options ) ) {
4610 $new_cmp = '<=';
4611 }
4612 if ( in_array( 'include_both', $options ) ) {
4613 $old_cmp = '>=';
4614 $new_cmp = '<=';
4615 }
4616 // No DB query needed if $old and $new are the same or successive revisions:
4617 if ( $old->getId() === $new->getId() ) {
4618 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4619 [] :
4620 [ $old->getUserText( Revision::RAW ) ];
4621 } elseif ( $old->getId() === $new->getParentId() ) {
4622 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4623 $authors[] = $old->getUserText( Revision::RAW );
4624 if ( $old->getUserText( Revision::RAW ) != $new->getUserText( Revision::RAW ) ) {
4625 $authors[] = $new->getUserText( Revision::RAW );
4626 }
4627 } elseif ( $old_cmp === '>=' ) {
4628 $authors[] = $old->getUserText( Revision::RAW );
4629 } elseif ( $new_cmp === '<=' ) {
4630 $authors[] = $new->getUserText( Revision::RAW );
4631 }
4632 return $authors;
4633 }
4634 $dbr = wfGetDB( DB_REPLICA );
4635 $revQuery = Revision::getQueryInfo();
4636 $authors = $dbr->selectFieldValues(
4637 $revQuery['tables'],
4638 $revQuery['fields']['rev_user_text'],
4639 [
4640 'rev_page' => $this->getArticleID(),
4641 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4642 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4643 ], __METHOD__,
4644 [ 'DISTINCT', 'LIMIT' => $limit + 1 ], // add one so caller knows it was truncated
4645 $revQuery['joins']
4646 );
4647 return $authors;
4648 }
4649
4650 /**
4651 * Get the number of authors between the given revisions or revision IDs.
4652 * Used for diffs and other things that really need it.
4653 *
4654 * @param int|Revision $old Old revision or rev ID (first before range by default)
4655 * @param int|Revision $new New revision or rev ID (first after range by default)
4656 * @param int $limit Maximum number of authors
4657 * @param string|array $options (Optional): Single option, or an array of options:
4658 * 'include_old' Include $old in the range; $new is excluded.
4659 * 'include_new' Include $new in the range; $old is excluded.
4660 * 'include_both' Include both $old and $new in the range.
4661 * Unknown option values are ignored.
4662 * @return int Number of revision authors in the range; zero if not both revisions exist
4663 */
4664 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4665 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4666 return $authors ? count( $authors ) : 0;
4667 }
4668
4669 /**
4670 * Compare with another title.
4671 *
4672 * @param Title $title
4673 * @return bool
4674 */
4675 public function equals( Title $title ) {
4676 // Note: === is necessary for proper matching of number-like titles.
4677 return $this->mInterwiki === $title->mInterwiki
4678 && $this->mNamespace == $title->mNamespace
4679 && $this->mDbkeyform === $title->mDbkeyform;
4680 }
4681
4682 /**
4683 * Check if this title is a subpage of another title
4684 *
4685 * @param Title $title
4686 * @return bool
4687 */
4688 public function isSubpageOf( Title $title ) {
4689 return $this->mInterwiki === $title->mInterwiki
4690 && $this->mNamespace == $title->mNamespace
4691 && strpos( $this->mDbkeyform, $title->mDbkeyform . '/' ) === 0;
4692 }
4693
4694 /**
4695 * Check if page exists. For historical reasons, this function simply
4696 * checks for the existence of the title in the page table, and will
4697 * thus return false for interwiki links, special pages and the like.
4698 * If you want to know if a title can be meaningfully viewed, you should
4699 * probably call the isKnown() method instead.
4700 *
4701 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4702 * from master/for update
4703 * @return bool
4704 */
4705 public function exists( $flags = 0 ) {
4706 $exists = $this->getArticleID( $flags ) != 0;
4707 Hooks::run( 'TitleExists', [ $this, &$exists ] );
4708 return $exists;
4709 }
4710
4711 /**
4712 * Should links to this title be shown as potentially viewable (i.e. as
4713 * "bluelinks"), even if there's no record by this title in the page
4714 * table?
4715 *
4716 * This function is semi-deprecated for public use, as well as somewhat
4717 * misleadingly named. You probably just want to call isKnown(), which
4718 * calls this function internally.
4719 *
4720 * (ISSUE: Most of these checks are cheap, but the file existence check
4721 * can potentially be quite expensive. Including it here fixes a lot of
4722 * existing code, but we might want to add an optional parameter to skip
4723 * it and any other expensive checks.)
4724 *
4725 * @return bool
4726 */
4727 public function isAlwaysKnown() {
4728 $isKnown = null;
4729
4730 /**
4731 * Allows overriding default behavior for determining if a page exists.
4732 * If $isKnown is kept as null, regular checks happen. If it's
4733 * a boolean, this value is returned by the isKnown method.
4734 *
4735 * @since 1.20
4736 *
4737 * @param Title $title
4738 * @param bool|null $isKnown
4739 */
4740 Hooks::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4741
4742 if ( !is_null( $isKnown ) ) {
4743 return $isKnown;
4744 }
4745
4746 if ( $this->isExternal() ) {
4747 return true; // any interwiki link might be viewable, for all we know
4748 }
4749
4750 switch ( $this->mNamespace ) {
4751 case NS_MEDIA:
4752 case NS_FILE:
4753 // file exists, possibly in a foreign repo
4754 return (bool)wfFindFile( $this );
4755 case NS_SPECIAL:
4756 // valid special page
4757 return MediaWikiServices::getInstance()->getSpecialPageFactory()->
4758 exists( $this->mDbkeyform );
4759 case NS_MAIN:
4760 // selflink, possibly with fragment
4761 return $this->mDbkeyform == '';
4762 case NS_MEDIAWIKI:
4763 // known system message
4764 return $this->hasSourceText() !== false;
4765 default:
4766 return false;
4767 }
4768 }
4769
4770 /**
4771 * Does this title refer to a page that can (or might) be meaningfully
4772 * viewed? In particular, this function may be used to determine if
4773 * links to the title should be rendered as "bluelinks" (as opposed to
4774 * "redlinks" to non-existent pages).
4775 * Adding something else to this function will cause inconsistency
4776 * since LinkHolderArray calls isAlwaysKnown() and does its own
4777 * page existence check.
4778 *
4779 * @return bool
4780 */
4781 public function isKnown() {
4782 return $this->isAlwaysKnown() || $this->exists();
4783 }
4784
4785 /**
4786 * Does this page have source text?
4787 *
4788 * @return bool
4789 */
4790 public function hasSourceText() {
4791 if ( $this->exists() ) {
4792 return true;
4793 }
4794
4795 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4796 // If the page doesn't exist but is a known system message, default
4797 // message content will be displayed, same for language subpages-
4798 // Use always content language to avoid loading hundreds of languages
4799 // to get the link color.
4800 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
4801 list( $name, ) = MessageCache::singleton()->figureMessage(
4802 $contLang->lcfirst( $this->getText() )
4803 );
4804 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4805 return $message->exists();
4806 }
4807
4808 return false;
4809 }
4810
4811 /**
4812 * Get the default (plain) message contents for an page that overrides an
4813 * interface message key.
4814 *
4815 * Primary use cases:
4816 *
4817 * - Article:
4818 * - Show default when viewing the page. The Article::getSubstituteContent
4819 * method displays the default message content, instead of the
4820 * 'noarticletext' placeholder message normally used.
4821 *
4822 * - EditPage:
4823 * - Title of edit page. When creating an interface message override,
4824 * the editor is told they are "Editing the page", instead of
4825 * "Creating the page". (EditPage::setHeaders)
4826 * - Edit notice. The 'translateinterface' edit notice is shown when creating
4827 * or editing a an interface message override. (EditPage::showIntro)
4828 * - Opening the editor. The contents of the localisation message are used
4829 * as contents of the editor when creating a new page in the MediaWiki
4830 * namespace. This simplifies the process for editors when "changing"
4831 * an interface message by creating an override. (EditPage::getContentObject)
4832 * - Showing a diff. The left-hand side of a diff when an editor is
4833 * previewing their changes before saving the creation of a page in the
4834 * MediaWiki namespace. (EditPage::showDiff)
4835 * - Disallowing a save. When attempting to create a a MediaWiki-namespace
4836 * page with the proposed content matching the interface message default,
4837 * the save is rejected, the same way we disallow blank pages from being
4838 * created. (EditPage::internalAttemptSave)
4839 *
4840 * - ApiEditPage:
4841 * - Default content, when using the 'prepend' or 'append' feature.
4842 *
4843 * - SkinTemplate:
4844 * - Label the create action as "Edit", if the page can be an override.
4845 *
4846 * @return string|bool
4847 */
4848 public function getDefaultMessageText() {
4849 if ( $this->mNamespace != NS_MEDIAWIKI ) { // Just in case
4850 return false;
4851 }
4852
4853 list( $name, $lang ) = MessageCache::singleton()->figureMessage(
4854 MediaWikiServices::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4855 );
4856 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4857
4858 if ( $message->exists() ) {
4859 return $message->plain();
4860 } else {
4861 return false;
4862 }
4863 }
4864
4865 /**
4866 * Updates page_touched for this page; called from LinksUpdate.php
4867 *
4868 * @param string|null $purgeTime [optional] TS_MW timestamp
4869 * @return bool True if the update succeeded
4870 */
4871 public function invalidateCache( $purgeTime = null ) {
4872 if ( wfReadOnly() ) {
4873 return false;
4874 } elseif ( $this->mArticleID === 0 ) {
4875 return true; // avoid gap locking if we know it's not there
4876 }
4877
4878 $dbw = wfGetDB( DB_MASTER );
4879 $dbw->onTransactionPreCommitOrIdle(
4880 function () use ( $dbw ) {
4881 ResourceLoaderWikiModule::invalidateModuleCache(
4882 $this, null, null, $dbw->getDomainId() );
4883 },
4884 __METHOD__
4885 );
4886
4887 $conds = $this->pageCond();
4888 DeferredUpdates::addUpdate(
4889 new AutoCommitUpdate(
4890 $dbw,
4891 __METHOD__,
4892 function ( IDatabase $dbw, $fname ) use ( $conds, $purgeTime ) {
4893 $dbTimestamp = $dbw->timestamp( $purgeTime ?: time() );
4894 $dbw->update(
4895 'page',
4896 [ 'page_touched' => $dbTimestamp ],
4897 $conds + [ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4898 $fname
4899 );
4900 MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $this );
4901 }
4902 ),
4903 DeferredUpdates::PRESEND
4904 );
4905
4906 return true;
4907 }
4908
4909 /**
4910 * Update page_touched timestamps and send CDN purge messages for
4911 * pages linking to this title. May be sent to the job queue depending
4912 * on the number of links. Typically called on create and delete.
4913 */
4914 public function touchLinks() {
4915 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4916 if ( $this->mNamespace == NS_CATEGORY ) {
4917 DeferredUpdates::addUpdate(
4918 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4919 );
4920 }
4921 }
4922
4923 /**
4924 * Get the last touched timestamp
4925 *
4926 * @param IDatabase|null $db
4927 * @return string|false Last-touched timestamp
4928 */
4929 public function getTouched( $db = null ) {
4930 if ( $db === null ) {
4931 $db = wfGetDB( DB_REPLICA );
4932 }
4933 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4934 return $touched;
4935 }
4936
4937 /**
4938 * Get the timestamp when this page was updated since the user last saw it.
4939 *
4940 * @param User|null $user
4941 * @return string|null
4942 */
4943 public function getNotificationTimestamp( $user = null ) {
4944 global $wgUser;
4945
4946 // Assume current user if none given
4947 if ( !$user ) {
4948 $user = $wgUser;
4949 }
4950 // Check cache first
4951 $uid = $user->getId();
4952 if ( !$uid ) {
4953 return false;
4954 }
4955 // avoid isset here, as it'll return false for null entries
4956 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4957 return $this->mNotificationTimestamp[$uid];
4958 }
4959 // Don't cache too much!
4960 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4961 $this->mNotificationTimestamp = [];
4962 }
4963
4964 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
4965 $watchedItem = $store->getWatchedItem( $user, $this );
4966 if ( $watchedItem ) {
4967 $this->mNotificationTimestamp[$uid] = $watchedItem->getNotificationTimestamp();
4968 } else {
4969 $this->mNotificationTimestamp[$uid] = false;
4970 }
4971
4972 return $this->mNotificationTimestamp[$uid];
4973 }
4974
4975 /**
4976 * Generate strings used for xml 'id' names in monobook tabs
4977 *
4978 * @param string $prepend Defaults to 'nstab-'
4979 * @return string XML 'id' name
4980 */
4981 public function getNamespaceKey( $prepend = 'nstab-' ) {
4982 // Gets the subject namespace of this title
4983 $subjectNS = MWNamespace::getSubject( $this->mNamespace );
4984 // Prefer canonical namespace name for HTML IDs
4985 $namespaceKey = MWNamespace::getCanonicalName( $subjectNS );
4986 if ( $namespaceKey === false ) {
4987 // Fallback to localised text
4988 $namespaceKey = $this->getSubjectNsText();
4989 }
4990 // Makes namespace key lowercase
4991 $namespaceKey = MediaWikiServices::getInstance()->getContentLanguage()->lc( $namespaceKey );
4992 // Uses main
4993 if ( $namespaceKey == '' ) {
4994 $namespaceKey = 'main';
4995 }
4996 // Changes file to image for backwards compatibility
4997 if ( $namespaceKey == 'file' ) {
4998 $namespaceKey = 'image';
4999 }
5000 return $prepend . $namespaceKey;
5001 }
5002
5003 /**
5004 * Get all extant redirects to this Title
5005 *
5006 * @param int|null $ns Single namespace to consider; null to consider all namespaces
5007 * @return Title[] Array of Title redirects to this title
5008 */
5009 public function getRedirectsHere( $ns = null ) {
5010 $redirs = [];
5011
5012 $dbr = wfGetDB( DB_REPLICA );
5013 $where = [
5014 'rd_namespace' => $this->mNamespace,
5015 'rd_title' => $this->mDbkeyform,
5016 'rd_from = page_id'
5017 ];
5018 if ( $this->isExternal() ) {
5019 $where['rd_interwiki'] = $this->mInterwiki;
5020 } else {
5021 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
5022 }
5023 if ( !is_null( $ns ) ) {
5024 $where['page_namespace'] = $ns;
5025 }
5026
5027 $res = $dbr->select(
5028 [ 'redirect', 'page' ],
5029 [ 'page_namespace', 'page_title' ],
5030 $where,
5031 __METHOD__
5032 );
5033
5034 foreach ( $res as $row ) {
5035 $redirs[] = self::newFromRow( $row );
5036 }
5037 return $redirs;
5038 }
5039
5040 /**
5041 * Check if this Title is a valid redirect target
5042 *
5043 * @return bool
5044 */
5045 public function isValidRedirectTarget() {
5046 global $wgInvalidRedirectTargets;
5047
5048 if ( $this->isSpecialPage() ) {
5049 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
5050 if ( $this->isSpecial( 'Userlogout' ) ) {
5051 return false;
5052 }
5053
5054 foreach ( $wgInvalidRedirectTargets as $target ) {
5055 if ( $this->isSpecial( $target ) ) {
5056 return false;
5057 }
5058 }
5059 }
5060
5061 return true;
5062 }
5063
5064 /**
5065 * Get a backlink cache object
5066 *
5067 * @return BacklinkCache
5068 */
5069 public function getBacklinkCache() {
5070 return BacklinkCache::get( $this );
5071 }
5072
5073 /**
5074 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
5075 *
5076 * @return bool
5077 */
5078 public function canUseNoindex() {
5079 global $wgExemptFromUserRobotsControl;
5080
5081 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
5082 ? MWNamespace::getContentNamespaces()
5083 : $wgExemptFromUserRobotsControl;
5084
5085 return !in_array( $this->mNamespace, $bannedNamespaces );
5086 }
5087
5088 /**
5089 * Returns the raw sort key to be used for categories, with the specified
5090 * prefix. This will be fed to Collation::getSortKey() to get a
5091 * binary sortkey that can be used for actual sorting.
5092 *
5093 * @param string $prefix The prefix to be used, specified using
5094 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
5095 * prefix.
5096 * @return string
5097 */
5098 public function getCategorySortkey( $prefix = '' ) {
5099 $unprefixed = $this->getText();
5100
5101 // Anything that uses this hook should only depend
5102 // on the Title object passed in, and should probably
5103 // tell the users to run updateCollations.php --force
5104 // in order to re-sort existing category relations.
5105 Hooks::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
5106 if ( $prefix !== '' ) {
5107 # Separate with a line feed, so the unprefixed part is only used as
5108 # a tiebreaker when two pages have the exact same prefix.
5109 # In UCA, tab is the only character that can sort above LF
5110 # so we strip both of them from the original prefix.
5111 $prefix = strtr( $prefix, "\n\t", ' ' );
5112 return "$prefix\n$unprefixed";
5113 }
5114 return $unprefixed;
5115 }
5116
5117 /**
5118 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
5119 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
5120 * the db, it will return NULL.
5121 *
5122 * @return string|null|bool
5123 */
5124 private function getDbPageLanguageCode() {
5125 global $wgPageLanguageUseDB;
5126
5127 // check, if the page language could be saved in the database, and if so and
5128 // the value is not requested already, lookup the page language using LinkCache
5129 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage === false ) {
5130 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
5131 $linkCache->addLinkObj( $this );
5132 $this->mDbPageLanguage = $linkCache->getGoodLinkFieldObj( $this, 'lang' );
5133 }
5134
5135 return $this->mDbPageLanguage;
5136 }
5137
5138 /**
5139 * Get the language in which the content of this page is written in
5140 * wikitext. Defaults to content language, but in certain cases it can be
5141 * e.g. $wgLang (such as special pages, which are in the user language).
5142 *
5143 * @since 1.18
5144 * @return Language
5145 */
5146 public function getPageLanguage() {
5147 global $wgLang, $wgLanguageCode;
5148 if ( $this->isSpecialPage() ) {
5149 // special pages are in the user language
5150 return $wgLang;
5151 }
5152
5153 // Checking if DB language is set
5154 $dbPageLanguage = $this->getDbPageLanguageCode();
5155 if ( $dbPageLanguage ) {
5156 return wfGetLangObj( $dbPageLanguage );
5157 }
5158
5159 if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) {
5160 // Note that this may depend on user settings, so the cache should
5161 // be only per-request.
5162 // NOTE: ContentHandler::getPageLanguage() may need to load the
5163 // content to determine the page language!
5164 // Checking $wgLanguageCode hasn't changed for the benefit of unit
5165 // tests.
5166 $contentHandler = ContentHandler::getForTitle( $this );
5167 $langObj = $contentHandler->getPageLanguage( $this );
5168 $this->mPageLanguage = [ $langObj->getCode(), $wgLanguageCode ];
5169 } else {
5170 $langObj = Language::factory( $this->mPageLanguage[0] );
5171 }
5172
5173 return $langObj;
5174 }
5175
5176 /**
5177 * Get the language in which the content of this page is written when
5178 * viewed by user. Defaults to content language, but in certain cases it can be
5179 * e.g. $wgLang (such as special pages, which are in the user language).
5180 *
5181 * @since 1.20
5182 * @return Language
5183 */
5184 public function getPageViewLanguage() {
5185 global $wgLang;
5186
5187 if ( $this->isSpecialPage() ) {
5188 // If the user chooses a variant, the content is actually
5189 // in a language whose code is the variant code.
5190 $variant = $wgLang->getPreferredVariant();
5191 if ( $wgLang->getCode() !== $variant ) {
5192 return Language::factory( $variant );
5193 }
5194
5195 return $wgLang;
5196 }
5197
5198 // Checking if DB language is set
5199 $dbPageLanguage = $this->getDbPageLanguageCode();
5200 if ( $dbPageLanguage ) {
5201 $pageLang = wfGetLangObj( $dbPageLanguage );
5202 $variant = $pageLang->getPreferredVariant();
5203 if ( $pageLang->getCode() !== $variant ) {
5204 $pageLang = Language::factory( $variant );
5205 }
5206
5207 return $pageLang;
5208 }
5209
5210 // @note Can't be cached persistently, depends on user settings.
5211 // @note ContentHandler::getPageViewLanguage() may need to load the
5212 // content to determine the page language!
5213 $contentHandler = ContentHandler::getForTitle( $this );
5214 $pageLang = $contentHandler->getPageViewLanguage( $this );
5215 return $pageLang;
5216 }
5217
5218 /**
5219 * Get a list of rendered edit notices for this page.
5220 *
5221 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
5222 * they will already be wrapped in paragraphs.
5223 *
5224 * @since 1.21
5225 * @param int $oldid Revision ID that's being edited
5226 * @return array
5227 */
5228 public function getEditNotices( $oldid = 0 ) {
5229 $notices = [];
5230
5231 // Optional notice for the entire namespace
5232 $editnotice_ns = 'editnotice-' . $this->mNamespace;
5233 $msg = wfMessage( $editnotice_ns );
5234 if ( $msg->exists() ) {
5235 $html = $msg->parseAsBlock();
5236 // Edit notices may have complex logic, but output nothing (T91715)
5237 if ( trim( $html ) !== '' ) {
5238 $notices[$editnotice_ns] = Html::rawElement(
5239 'div',
5240 [ 'class' => [
5241 'mw-editnotice',
5242 'mw-editnotice-namespace',
5243 Sanitizer::escapeClass( "mw-$editnotice_ns" )
5244 ] ],
5245 $html
5246 );
5247 }
5248 }
5249
5250 if ( MWNamespace::hasSubpages( $this->mNamespace ) ) {
5251 // Optional notice for page itself and any parent page
5252 $editnotice_base = $editnotice_ns;
5253 foreach ( explode( '/', $this->mDbkeyform ) as $part ) {
5254 $editnotice_base .= '-' . $part;
5255 $msg = wfMessage( $editnotice_base );
5256 if ( $msg->exists() ) {
5257 $html = $msg->parseAsBlock();
5258 if ( trim( $html ) !== '' ) {
5259 $notices[$editnotice_base] = Html::rawElement(
5260 'div',
5261 [ 'class' => [
5262 'mw-editnotice',
5263 'mw-editnotice-base',
5264 Sanitizer::escapeClass( "mw-$editnotice_base" )
5265 ] ],
5266 $html
5267 );
5268 }
5269 }
5270 }
5271 } else {
5272 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
5273 $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform, '/', '-' );
5274 $msg = wfMessage( $editnoticeText );
5275 if ( $msg->exists() ) {
5276 $html = $msg->parseAsBlock();
5277 if ( trim( $html ) !== '' ) {
5278 $notices[$editnoticeText] = Html::rawElement(
5279 'div',
5280 [ 'class' => [
5281 'mw-editnotice',
5282 'mw-editnotice-page',
5283 Sanitizer::escapeClass( "mw-$editnoticeText" )
5284 ] ],
5285 $html
5286 );
5287 }
5288 }
5289 }
5290
5291 Hooks::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
5292 return $notices;
5293 }
5294
5295 /**
5296 * @return array
5297 */
5298 public function __sleep() {
5299 return [
5300 'mNamespace',
5301 'mDbkeyform',
5302 'mFragment',
5303 'mInterwiki',
5304 'mLocalInterwiki',
5305 'mUserCaseDBKey',
5306 'mDefaultNamespace',
5307 ];
5308 }
5309
5310 public function __wakeup() {
5311 $this->mArticleID = ( $this->mNamespace >= 0 ) ? -1 : 0;
5312 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
5313 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
5314 }
5315
5316 }